迫使DateTime.对不变日期的解析失败
本文关键字:失败 日期 DateTime 迫使 | 更新日期: 2023-09-27 18:06:04
我将简短地开始,然后在最后给出细节。考虑下面的代码:
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)
失败的文化调用新代码,然后显示更改的代码将成功。
问题是我还没有找到一个能为我做这件事的文化。我将尝试制造一个,但我想我应该先问一个更一般的问题。
使用以下代码:
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-Cyrl
bs-Cyrl-BA
bs-Lat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
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
对en-GB
抛出异常。
这是因为不变区域性数据格式设置为MM/dd/yyyy
。对于en-GB
,它是dd/MM/yyyy
,这意味着您试图解析日期,月份设置为13
,这是不正确的。
对于day小于13
的日期,将毫无例外地解析输入字符串,但结果将不正确(除非day和month是相同的数字)。