到现在为止,我认为我会理解 DateTime.ParseExact
的工作原理,但这令人困惑。为什么下一行返回 false
?
DateTime.TryParseExact("2013122", "yyyyMdd", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out lastUpdate)
月份也可以有两位数。我认为它应该能够理解它意味着2013年1月22日。为什么我走错了路?我是否遗漏了什么或者是否有简单的解决方法?
与此同时,我正在使用这个不是很优雅但有效的解决方法:
public static DateTime? ParseDate_yyyyMdd(String date)
{
if (date == null)
return null;
date = date.Trim();
if (date.Length < 7)
return null;
if (date.Length == 7)
date = date.Insert(4, "0");
DateTime dt;
if (DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
return dt;
return null;
}
给出我想要的结果:
DateTime? date = ParseDate_yyyyMdd("2013122");
Console.Write(date.ToString()); // 01/22/2013
但是,我仍然对这种限制的原因感兴趣。也许有人也有更好的方法。
最佳答案
来自 MSDN documentation :
If you do not use date or time separators in a custom format pattern, 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 pattern, specify the wider form, "HH", instead of the narrower form, "H".
我认为原因是它试图从左到右解析(没有回溯)。因为没有分隔符,所以无法确定日期部分的边界。
关于c# - DateTime.ParseExact 具有 7 位数字/一位或两位数字的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21902722/