强制DateTime.Parse为不变日期失败

时间:2014-05-30 01:08:31

标签: c# datetime cultureinfo datetime-parsing invariantculture

我会简短地开始,然后在最后提供细节。请考虑以下代码:

CultureInfo cultureToTest = new CultureInfo("hu-HU");
Thread.CurrentThread.CurrentCulture = cultureToTest;
DateTime testDateTime = new DateTime(2014,12,13,23,24,25);
String testString = testDateTime.ToString(CultureInfo.InvariantCulture);
DateTime actualDateTime = DateTime.Parse(testString);

问题是cultureToTest是否有任何可能导致DateTime.Parse调用抛出异常或返回错误值的值?


上下文

这是一组单元测试。有一段代码调用DateTime.Parse而没有指定文化。我担心的是,当这段代码在Invariant或en-US文化中被传递时,代码可能会在某些文化中失败。我建议的解决方案是将代码更改为使用

DateTime.Parse(string, CultureInfo.InvariantCulture)

在这些情况下。

为了对更改进行单元测试,我需要调用具有原始DateTime.Parse(string)失败的文化的新代码,然后显示更改的代码将成功。

问题在于我还没有找到一种能够为我做这件事的文化。我打算尝试制造一个,但我想我先问一般的问题。

2 个答案:

答案 0 :(得分:2)

使用此代码:

StringBuilder sb = new StringBuilder();
foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
    try
    {
        Thread.CurrentThread.CurrentCulture = culture;
        DateTime testDateTime = new DateTime(2014, 12, 13, 23, 24, 25);
        String testString = testDateTime.ToString(CultureInfo.InvariantCulture);
        DateTime actualDateTime = DateTime.Parse(testString);
        Console.WriteLine(actualDateTime.Day.ToString());
    }
    catch (Exception ex)
    {
       sb.AppendLine(culture.ToString());
    }
}

Console.WriteLine(sb.ToString());

以下文化在解析该日期时抛出异常:

am
am-ET
ar
ar-AE
ar-BH
ar-DZ
ar-EG
ar-IQ
ar-JO
ar-KW
ar-LB
ar-LY
ar-MA
ar-OM
ar-QA
ar-SA
ar-SY
ar-TN
ar-YE
arn
arn-CL
as
as-IN
az
az-Cyrl
az-Cyrl-AZ
az-Latn
az-Latn-AZ
ba
ba-RU
be
be-BY
bg
bg-BG
bn
bn-BD
bn-IN
br
br-FR
bs
bs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-RU
rw
rw-RW
sa
sa-IN
sah
sah-RU
sd
sd-Arab
sd-Arab-PK
se
se-FI
se-NO
sk
sk-SK
sl
sl-SI
sma-NO
smj-NO
smn
smn-FI
sms
sms-FI
sn
sn-Latn
sn-Latn-ZW
so
so-SO
sq
sq-AL
sr
sr-Cyrl
sr-Cyrl-BA
sr-Cyrl-CS
sr-Cyrl-ME
sr-Cyrl-RS
sr-Latn
sr-Latn-BA
sr-Latn-CS
sr-Latn-ME
sr-Latn-RS
sv-FI
syr
syr-SY
ta
ta-IN
ta-LK
te
te-IN
tg
tg-Cyrl
tg-Cyrl-TJ
th
th-TH
ti
ti-ER
ti-ET
tk
tk-TM
tn
tn-BW
tn-ZA
tr
tr-TR
tt
tt-RU
tzm
tzm-Latn
tzm-Latn-DZ
tzm-Tfng
tzm-Tfng-MA
uk
uk-UA
ur
ur-IN
ur-PK
uz
uz-Cyrl
uz-Cyrl-UZ
uz-Latn
uz-Latn-UZ
vi
vi-VN
wo
wo-SN
yo
yo-NG
zgh
zgh-Tfng
zgh-Tfng-MA
zh-Hant
zh-HK
zh-MO
zh-SG
zu
zu-ZA
zh-CHT

答案 1 :(得分:1)

它会引发en-GB的异常。

这是因为不变文化数据格式设置为MM/dd/yyyy。对于en-GB dd/MM/yyyy,这意味着您尝试将日期设置为13,这是不正确的。

对于日期低于13的日期,将毫无例外地解析输入字符串,但结果将不正确(除非日期和月份是相同的数字)。