问题 DateTime.ParseExact,包含7位数字/一个月或两位数月份


到现在为止我以为我会理解如何 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

但是,我仍然对这种限制的原因感兴趣。也许有人也有更好的方法。


4835
2018-02-20 08:55


起源

我认为答案是正确的,但这对我来说似乎仍然很奇怪。我不明白 最宽 规则。你是说 嘿,尝试解析我的前4个角色作为一年,在1个角色作为一个月后,在2个角色作为一天。但方法忽略了它。 - Soner Gönül
..它说: hey, your string doesn't have date separator, and that's why I ignore your format because it doesn't have widest form of your specifiers。 - Soner Gönül
如果你使用 ""yyyyMd" 相反,它解析,但错误的解释, lastUpdate= 2013 / DEC / 2。 - Jeppe Stig Nielsen
你的解决方法可能有点不那么难看: if (date.Length == 7) { date = date.Insert(4, "0"); } - Jeppe Stig Nielsen
我关于这个问题连接到.NET Framework团队,并且 他们的回应。 - Soner Gönül


答案:


MSDN文档

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

我认为原因是它试图从左到右解析(没有回溯)。由于没有分隔符,因此无法确定日期部分的边界。


5
2018-02-20 09:04



你试过这样转换吗?它仍然返回false yyyyMMdd - Ondrej Janacek
@OndrejJanacek它回来了 true 同 yyyyMMd。您的格式需要8个字符,其中7个字符的字符串。 - Soner Gönül
@SonerGönül但它没有按预期解析 - Plue
@Plue实际上是。同 yyyyMMd 你得到的格式 02.12.2013 (2013年12月2日)。 Ondrej的格式没有解析它们中的任何一个,因为它至少与它不是相同的长度 "2013122" - Soner Gönül
@SonerGönül那么你如何获得 2013年1月22日 从 2013122? - Plue


http://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx

如果不在自定义格式模式中使用日期或时间分隔符,请使用provider参数的不变区域性和 每种自定义格式说明符的最宽泛形式。例如,如果要在模式中指定小时数,请指定较宽的形式“HH”,而不是较窄的形式“H”。


2
2018-02-20 09:03





我在源代码中找到了它。这证实了活动挂图和Mark Sturgill的答案。

在某处调用内部ParseByFormat,它会计算(在您的情况下)'M':

    // System.DateTimeParse
    private static bool ParseByFormat(ref __DTString str, ref __DTString format, ref ParsingInfo parseInfo, DateTimeFormatInfo dtfi, ref DateTimeResult result)
    {   
        ...
        case 'M':
            num = format.GetRepeatCount();
            if (num <= 2)
            {
                if (!DateTimeParse.ParseDigits(ref str, num, out newValue2) && (!parseInfo.fCustomNumberParser || !parseInfo.parseNumberDelegate(ref str, num, out newValue2)))
                {
                    result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
                    return false;
                }
            }

下一个调用不是很有趣,除了ParseDigits调用中的2个小数字:

    // System.DateTimeParse
    internal static bool ParseDigits(ref __DTString str, int digitLen, out int result)
    {
        if (digitLen == 1)
        {
            return DateTimeParse.ParseDigits(ref str, 1, 2, out result);
        }
        return DateTimeParse.ParseDigits(ref str, digitLen, digitLen, out result);
    }

但现在我们来到有趣的部分:

    // System.DateTimeParse
    internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int result)
    {
        result = 0;
        int index = str.Index;
        int i;
        for (i = 0; i < maxDigitLen; i++)
        {
            if (!str.GetNextDigit())
            {
                str.Index--;
                break;
            }
            result = result * 10 + str.GetDigit();
        }
        if (i < minDigitLen)
        {
            str.Index = index;
            return false;
        }
        return true;
    }

这意味着(已经回答):

如果不使用最大位数且下一个字符也是数字,则格式无效。这是以下返回true的原因:

DateTime.TryParseExact("20131-22", "yyyyM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out lastUpdate)

不要问我这个限制的原因 - 它只是在源代码中。


2
2018-02-20 10:19



打败我。我只是在查看来源:D - flipchart
+1感谢您的分析。但是应该在文档中更明确地提到它。我希望这会在某个时候得到解决。 - Tim Schmelter