C# : Convert datetime from string with different format

戏子无情 提交于 2019-11-28 08:59:32

问题


If my string is 26/01/2011 00:14:00 but my computer set United state format (AM:PM) How to convert my string into Datetime? I try Convert.ToDateTime() but it cause error.


回答1:


As the others have said, you can use DateTime.TryParseExact, but you also seem to have a European culture format in your date. It might not hurt to make an attempt to use that to perform the conversion:

CultureInfo enGB = new CultureInfo("en-GB"); 
string dateString;
DateTime dateValue;

// Parse date with no style flags.
dateString = "26/01/2011 00:14:00";
DateTime.TryParseExact(dateString, "g", enGB, DateTimeStyles.None, out dateValue);



回答2:


Use DateTime.ParseExact or DateTime.TryParseExact. If you have to accept multiple possible datetime formats, both of those methods have overloads that take an array of format strings.

As far as that format, it looks like "dd/mm/yyyy HH:MM:ss"




回答3:


I use DateTime.Tryparse - that way you can catch and handle a failure gracefully:

http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx



来源:https://stackoverflow.com/questions/4796796/c-sharp-convert-datetime-from-string-with-different-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!