简体   繁体   English

如何在c#中将字符串转换为特定的DateTime格式?

[英]How to convert a string to a specific DateTime format in c#?

How to convert the string "28/09/2009" to DateTime in a specific format? 如何将字符串"28/09/2009"以特定格式转换为DateTime Ex: I want to convert "2009-09-28 17:30:40" to DateTime. 例如:我想将“2009-09-28 17:30:40”转换为DateTime。 I want to convert "28/09/2009 17:30:40" to DateTime. 我想将“28/09/2009 17:30:40”转换为DateTime。 I want to convert "20090928 17:30:40" to DateTime. 我想将“20090928 17:30:40”转换为DateTime。

There are multiple possible formats. 有多种可能的格式。 I tried this: 我试过这个:

string[] formats = new string[] {"yyyymmdd","yyyymmddThhmmss","yyyy/mm/dd  hh:mm:ss","yyyy/mm/dd","yyyy-mm-dd hh:mm:ss","yyyy-mm-dd"};
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime formattedDate = DateTime.ParseExact(aDate, formats, culture, DateTimeStyles.None);

This example throws an exception with the message "String was not recognized as a valid DateTime". 此示例引发异常,并显示消息“String未被识别为有效的DateTime”。

What's wrong in the code above? 上面的代码有什么问题?

None of your formats put the day first, like this: "dd/MM/yyyy" . 你的格式都不是第一天,比如: "dd/MM/yyyy"

Also note the capital 'M', since lower case 'm' is for 'minutes'. 还要注意首都'M',因为小写'm'代表'分钟'。 You have a similar problem with your hours; 您的工作时间也有类似的问题; since your samples all use 24 hour time you need a capital 'H'. 由于你的样品全部使用24小时,你需要一个大写'H'。

Your format string array should look like this: 您的格式字符串数组应如下所示:

string[] formats = {"dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "yyyyMMdd HH:mm:ss"};

Those formats exactly match your supplied sample strings. 这些格式与提供的示例字符串完全匹配。

Additionally, you probably want to use the invariant culture rather than en-US in this case. 此外,在这种情况下,您可能希望使用不变文化而不是en-US Otherwise, the '/' character in your format strings is really a culture-specific date separator, which a user might over-ride on their local system. 否则,格式字符串中的“/”字符实际上是特定于文化的日期分隔符,用户可能会在其本地系统上覆盖该字符串。

Finally, since you're obviously having trouble matching up the strings up, you might want to use TryParseExact() , which works just like parse exact but uses an out parameter rather than returning the value, so that it can return a boolean to indicate success or failure rather than throwing an exception. 最后,因为你显然无法匹配字符串,你可能想要使用TryParseExact() ,它就像解析精确但是使用out参数而不是返回值,因此它可以返回一个布尔值来指示成功或失败,而不是抛出异常。

See the complete format string reference here: 请参阅此处的完整格式字符串参考:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM