DateTime.TryParseExact未正常工作 [英] DateTime.TryParseExact not working as expected
问题描述
任何人都可以解释为什么下面的代码片段返回true?
Can anyone explain why the following snippet returns true?
根据文档的的中的d自定义格式说明,一个单一的数字一天不带前导零的格式。那么,为什么不TryParseExact时,我给它一个个位数的一天,一个前导零
According to the docs for The "d" custom format specifier, "A single-digit day is formatted without a leading zero." So why doesn't TryParseExact fail when I give it a single-digit day with a leading zero?
DateTime x;
return DateTime.TryParseExact
(
"01/01/2001",
@"d\/MM\/yyyy",
null,
System.Globalization.DateTimeStyles.None,
out x
);
更新
我想,也许我还不清楚最初。我真的很想要知道的就是:为什么TryParseExact所有我看到的文档接受不完全匹配一些值,'D'匹配'01'和'1'是一样多,如果'MM'匹配三八以及03的错误。 这里的问题不说,价值观是等价的,它是不匹配的格式。
I think maybe I was unclear originally. What I am really trying to get at is: Why does TryParseExact accept some values that don't match exactly? from all of the documentation I have seen, 'd' matching '01' and '1' is just as much a bug as if 'MM' matched 'March' as well as '03'. The issue here isn't that the values are equivalent, its that they don't match the format.
文件的有关片段是
-
从的 TryParseExact :字符串表示的格式必须指定格式完全相同
通过的'D'说明:单数字的日期格式没有前导零。
这似乎非常清楚,我认为'01'具有领先的0的,因此不完全匹配'D'。
It seems abundantly clear to me that '01' has a leading 0, and therefore doesn't exactly match 'd'.
推荐答案
从.NET 4源DateTimeParse.ParseByFormat():
From the .NET 4 source in DateTimeParse.ParseByFormat():
case 'd':
// Day & Day of week
tokenLen = format.GetRepeatCount();
if (tokenLen <= 2) {
// "d" & "dd"
if (!ParseDigits(ref str, tokenLen, out tempDay)) {
if (!parseInfo.fCustomNumberParser ||
!parseInfo.parseNumberDelegate(ref str, tokenLen, out tempDay)) {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return (false);
}
}
if (!CheckNewValue(ref result.Day, tempDay, ch, ref result)) {
return (false);
}
}
else
{...}
解析器肿块D和DD在一起。
The parser lumps "d" and "dd" together.
这篇关于DateTime.TryParseExact未正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!