DateTime.ParseExact有7位/一或两个数字的月份 [英] DateTime.ParseExact with 7 digits / one or two digit month

查看:444
本文介绍了DateTime.ParseExact有7位/一或两个数字的月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到现在为止我还以为我了解 DateTime.ParseExact 的作品,但是这是令人困惑的。为什么下面一行返回

Until now i thought that i would understand how DateTime.ParseExact works, but this is confusing. Why does following line returns false?

DateTime.TryParseExact("2013122", "yyyyMdd", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out lastUpdate)

月份也可以有两个数字。在我看来,它应该能明白这意味着1月22日2013年为什么我在错误的轨道上吗?我错过了什么或者是有一个简单的解决方法吗?

The month can also have two digits. In my opinion it should be able to understand that it means 22 January 2013. Why i'm on the wrong track? Did I miss something or is there an easy workaround?

同时我使用这种解决方法这是不是很优雅,但作品:

Meanwhile i'm using this workaround which is not very elegant but works:

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;
}

给出我想要的结果:

Gives my desired result:

DateTime? date = ParseDate_yyyyMdd("2013122");
Console.Write(date.ToString()); // 01/22/2013

不过,我仍然有兴趣在此限制的原因。也许有人也有一个更好的办法。

However, i'm still interested in the reason for this limitation. Maybe someone also has a better approach.

推荐答案

从的 MSDN文档

如果你不使用的日期或时间分隔符自定义格式模式,使用固定区域性的供应商参数,每一个自定义格式说明的最广泛的形式。例如,如果要在模式指定小时,指定较宽的形式,HH,而不是窄形,H,

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".

我认为,原因在于它试图解析从左到右(不回溯)。因为没有分隔符,它不能确定日期部分的界限。

I think that the reason is that it tries to parse left to right (without backtracking). Because there are no delimiters, it can't determine the boundaries of the date parts.

这篇关于DateTime.ParseExact有7位/一或两个数字的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆