简体   繁体   English

解析自定义日期时间格式

[英]Parsing Custom DateTime Format

I have to parse DateTime objects from strings with the yyyyMMddhhmmss format. 我必须使用yyyyMMddhhmmss格式从字符串中解析DateTime对象。

If I run this code, it works fine: 如果我运行此代码,它可以正常工作:

DateTime y = new DateTime(2013, 07, 22, 15, 35, 23);
string x = y.ToString("yyyyMMddhhmmss", CultureInfo.InvariantCulture);

But if I run this code - seemingly the inverse operation - I get an exception: 但是,如果我运行此代码 - 看似相反的操作 - 我得到一个例外:

string x = "20130722153523";
DateTime y = DateTime.ParseExact(x, "yyyyMMddhhmmss", CultureInfo.InvariantCulture);

The exception is: 例外是:

System.FormatException: String was not recognized as a valid DateTime.

I'm stumped as to what's wrong here. 我很难过这里有什么不对劲。 What am I doing wrong? 我究竟做错了什么?

Note: Don't worry about timezones. 注意:不要担心时区。 I can deal with getting the correct timezone later. 我可以稍后处理获得正确的时区。

The problem is that the date-time format you specified uses hh for a 12-hour time format, but the input string has 15 in that area. 问题是您指定的日期时间格式使用hh表示12小时时间格式,但输入字符串在该区域中有15 It can't parse this because 15 is outside the expected range. 它无法解析这个因为15超出预期范围。

Try using HH for a 24-hour time format instead: 尝试使用HH作为24小时时间格式:

string x = "20130722153523";
DateTime y = DateTime.ParseExact(x, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

Further Reading: 进一步阅读:

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

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