如何转换" 24-04-2015 00:00:00"字符串到c#中的日期时间?

时间:2017-08-22 11:03:52

标签: asp.net c#-4.0

我有字符串"24-04-2015 00:00:00"。我需要将它转换为datetime并将其存储在数据库中。

如果我将"24-04-2015 00:00:00"作为字符串传递给数据库,我收到错误

  

"无法将参数值从String转换为DateTime。"

如果我使用DateTime.ParseExact("24-04-2015 00:00:00", "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);  我收到了以下错误

  

字符串未被识别为有效的DateTime。

1 个答案:

答案 0 :(得分:1)

尝试以下:

//Add namespace 
using System.Globalization;

// Code to convert the string to datetime
string datetime="24-04-2015 00:00:00";
DateTime dt = DateTime.ParseExact(datetime, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);

以上代码经过测试。