日期时间格式问题:字符串未被识别为有效的DateTime [英] Datetime format Issue: String was not recognized as a valid DateTime
问题描述
我想将输入字符串格式化为C#中的 MM / dd / yyyy hh:mm:ss 格式。
输入字符串格式为 MM / dd / yyyy hh:mm:ss
例如:04/30/2013 23:00
I want to format the input string into MM/dd/yyyy hh:mm:ss format in C#.
The input string is in format MM/dd/yyyy hh:mm:ss
For example :"04/30/2013 23:00"
我尝试过 Convert.ToDateTime()
函数,但它将4作为日期和3作为月份这不是我想要的。实际上月份是04,日期是03。
I tried Convert.ToDateTime()
function, but it considers 4 as date and 3 as month which is not what I want. Actually month is 04 and date is 03.
我尝试了 DateTime.ParseExact()
函数,但是获取异常
I tried DateTime.ParseExact()
function also, But getting Exception.
我收到错误:
字符串未被识别为有效DateTime。
String was not recognized as a valid DateTime.
推荐答案
您的日期时间字符串不包含任何秒。您需要以格式反映(删除:ss
)。
此外,您需要指定 H
而不是 h
如果您正在使用24小时的时间:
Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss
).
Also, you need to specify H
instead of h
if you are using 24 hour times:
DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)
请参阅这里了解更多信息:
See here for more information:
这篇关于日期时间格式问题:字符串未被识别为有效的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!