如何将诸如2009-05-08 14:40:52,531这样的字符串转换为DateTime?


当前回答

世界上不同的文化以不同的方式书写日期字符串。例如,在美国01/20/2008就是2008年1月20日。在法国,这将抛出InvalidFormatException异常。这是因为法国的日期时间是日/月/年,而美国的日期时间是月/日/年。

因此,像20/01/2008这样的字符串在法国将解析到2008年1月20日,然后在美国抛出InvalidFormatException。

要确定当前区域性设置,可以使用System.Globalization.CultureInfo.CurrentCulture。

string dateTime = "01/08/2008 14:50:50.42";  
        DateTime dt = Convert.ToDateTime(dateTime);  
        Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour: {3}, Minute: {4}, Second: {5}, Millisecond: {6}",  
                          dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);  

其他回答

试试这个

DateTime myDate = DateTime.Parse(dateString);

一个更好的方法是:

DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
    // handle parse failure
}

我尝试了各种方法。对我有用的是:

Convert.ToDateTime(data, CultureInfo.InvariantCulture);

我的数据是2017年9月24日上午9:31:34

String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);

这个给了你

2019-08-17 11:14:49.000

你基本上有两个选择。DateTime.Parse()和DateTime.ParseExact()。

第一个在语法方面非常宽容,将以许多不同的格式解析日期。它对可能以不同格式出现的用户输入很有帮助。

ParseExact将允许您指定用于解析的日期字符串的确切格式。如果您的字符串总是使用相同的格式,那么使用这个是很好的。通过这种方式,您可以轻松地检测出与预期数据的任何偏差。

你可以这样解析用户输入:

DateTime enteredDate = DateTime.Parse(enteredString);

如果你有一个特定的字符串格式,你应该使用另一种方法:

DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);

“d”代表短日期模式(更多信息请参阅MSDN), null指定当前区域性应用于解析字符串。

如果您不确定输入值,也可以如下所示使用DateTime.TryParseExact()。

DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
    return outputDateTimeValue;
}
else
{
    // Handle the fact that parse did not succeed
}