.Net DateTime.ParseExact 不起作用

本文关键字:不起作用 ParseExact DateTime Net | 更新日期: 2023-09-27 18:36:58

以下解析是否有效,

DateTime.ParseExact("20150105 91353", "yyyyMMdd Hmmss", CultureInfo.InvariantCulture);;

我发现上面的不起作用,而下面的工作,

DateTime.ParseExact("20150105 091353", "yyyyMMdd HHmmss", CultureInfo.InvariantCulture);;

我想知道第一行代码有什么问题。

.Net DateTime.ParseExact 不起作用

这是

Custom DateTime格式可能会发现输入不明确的特殊情况之一。

当小时和分钟之间没有分隔符时,单个H格式无法区分第二个数字属于小时或分钟,因此解析失败。

91353 //interpreted either as 9 13 53 or 91 35 3 - which one? ambiguous -> error

但这没关系:

string str = "20150105 9:13:53"; //no ambiguity with format yyyyMMdd H:mm:ss
string fmt = "yyyyMMdd H:mm:ss"; //can handle both "20150105 9:13:53" and "20150105 09:13:53"
DateTime dt = DateTime.ParseExact(str, fmt, CultureInfo.InvariantCulture);

要解决它,请尝试对您的原始string进行少量操作。

string dtstr = "20150105 91353";
string fmt = "yyyyMMdd Hmmss";
string[] parts = dtstr.Split(' ');
string str = parts[1].Length < 6 ? string.Join(" 0", parts) : dtstr;
DateTime dt = DateTime.ParseExact(str, fmt, CultureInfo.InvariantCulture);

那么它应该没问题。

根据MSDN

如果不在自定义格式模式中使用日期或时间分隔符,请对提供程序参数使用固定区域性和每个自定义格式说明符的最宽形式。例如,如果要在模式中指定小时数,请指定较宽的形式"HH",而不是较窄的形式"H"。

这意味着这是正确的DateTime.ParseExact("20150105 9:13:53", "yyyyMMdd H:mm:ss", CultureInfo.InvariantCulture);因为它使用了时间分隔符