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


当前回答

string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);

//////// this methods convert string value to datetime
///////// in order to print date

Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);

其他回答

转换。ToDateTime或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))

世界上不同的文化以不同的方式书写日期字符串。例如,在美国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);  
String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);

这个给了你

2019-08-17 11:14:49.000