DateTime奇怪的错误

时间:2011-05-12 11:50:17

标签: asp.net localization

DateTime? billDateFrom = string.IsNullOrWhiteSpace(txtBillDateFrom.Text) ? null : (DateTime?)DateTime.Parse(txtBillDateFrom.Text);

txtBillDateFrom.Text等于“05/26/2011”。 (2011年5月26日)

此代码仅在Web应用程序中抛出错误“String未被识别为有效的DateTime”。在控制台应用程序中它运行良好。 为什么?它取决于区域设置吗?

5 个答案:

答案 0 :(得分:4)

是的,Parse()的行为取决于当前线程的文化。无论文化如何,您都可以使用ParseExact()使该行为保持一致:

DateTime.ParseExact(txtBillDateFrom.Text, "d", CultureInfo.InvariantCulture)

答案 1 :(得分:2)

是的。您可以更改主题的文化,或获取所需语言区域的CultureInfo并将其DateTimeFormat传递给DateTime.Parse

// Setting in thread
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
DateTime dt1 = DateTime.Parse("05/26/2011");
// Only for 1 parse
DateTime dt2 = DateTime.Parse("05/26/2011", System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);

我也相信你可以在asp.net应用程序的设置中设置文化。

<system.web>
    <globalization culture="en-US"/>
</system.web>

答案 2 :(得分:1)

是的,这取决于区域设置。

您可以在web.config文件中指定要使用的区域设置,也可以在对Parse的调用中指定它:

DateTime.Parse(txtBillDateFrom.Text, CultureInfo.GetCultureInfo("en-GB"))

答案 3 :(得分:0)

这取决于当前的文化。在web.config中,您可以设置所需的文化:

<globalization uiCulture="it" culture="it-IT" />

答案 4 :(得分:-2)

尝试下面

 DateTime dt;
        DateTime.TryParse("05/26/2011", out dt);