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


当前回答

我只是找到了一个优雅的方法:

Convert.ChangeType("2020-12-31", typeof(DateTime));

Convert.ChangeType("2020/12/31", typeof(DateTime));

Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));

Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));

Convert.ChangeType("11/شعبان/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));

Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"

其他回答

试试下面的方法,strDate是你的日期,格式为'MM/dd/yyyy'

var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))

使用DateTime.Parse(字符串):

DateTime dateTime = DateTime.Parse(dateTimeStr);

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

Convert.ToDateTime(data, CultureInfo.InvariantCulture);

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

我只是找到了一个优雅的方法:

Convert.ChangeType("2020-12-31", typeof(DateTime));

Convert.ChangeType("2020/12/31", typeof(DateTime));

Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));

Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));

Convert.ChangeType("11/شعبان/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));

Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"

世界上不同的文化以不同的方式书写日期字符串。例如,在美国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);