c# - DateTime.ParseExact 具有 7 位数字/一位或两位数字的月份

标签 c# .net parsing datetime

到现在为止,我认为我会理解 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/

相关文章:

c# - 将未知值传递到 switch 语句时,我应该抛出什么类型的异常

c# - 使用 C# 将应用程序洞察中的自定义事件数据获取到数组中

c# - 具有默认值的 DateTime 的 Fluent NHibernate 映射

c# - 是否可以在 C# 中更改对象类型

java - 尝试将多个字符串解析为 1 个字符串

c# - 如何处理捕获的异常

.net - .NET 断言类型

c# - 如何在 Windows Phone 8 应用程序中使用 Paypal 进行交易?

java - 自动从json创建java对象?

javascript - 为什么这个 HTML 标签甚至在 body 加载之前就将 body 作为它的 lastChild