如何解析具有非标准格式 (yyyyMMdd:Hmm) 的日期时间?

How can I parse a datetime with a nonstandard format (yyyyMMdd:Hmm)?

我们有一个集成合作伙伴坚持以 yyyyMMdd:Hmm 格式的字符串形式向我们发送日期时间,例如“20211029:102”。请注意,小时没有前导零。

我试着这样解析它:

Datetime datetime = DateTime.ParseExact(
   "20211029:102", 
   "yyyyMMdd:hmm", 
   CultureInfo.InvariantCulture, 
   DateTimeStyles.None
);

但这会导致

FormatException••• String '20211029:102' was not recognized as a valid DateTime.

我可以通过重新添加缺失的零来使其工作,例如:

string datetimeParts = "20211029:102".Split(":");
string value = datetimeParts[0] + datetimeParts[1].PadLeft(4, '0');
Datetime dt = DateTime.ParseExact(
    value, 
    "yyyyMMddHHmm", 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None
);

但我觉得我不需要“预解析”该值。是否可以在不进行预处理的情况下解析这种格式?

问题出在你的格式字符串的时间部分,所以我的回答将解释为什么你不能用格式字符串Hmm解析102(我知道你写了 hmm,但由于你没有 AM/PM 指示符,我假设你打算改为写 Hmm。同样的推理适用于 hmm.)

如果我们看the reference source, we can see that the DateTime parser is "greedy": If the parser encounters a single-letter format specifier (such as H), it will still try to consume 2 digits, if two digits are available.

在您的情况下,两位数字 可用 ,因此 H 将消耗 10102。这只会在一分钟内留下 2,它不会匹配 mm(因为它只有一个数字)。

鉴于此限制,无法解析格式为 HmmDateTime.ParseExact 的 DateTime 值。 The documentation 注释如下:

Note

If format is a custom format pattern that does not include date or time separators (such as "yyyyMMddHHmm"), use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the format pattern, specify the wider form, "HH", instead of the narrower form, "H".