开发者

DateTime strange error

开发者 https://www.devze.com 2023-03-05 15:24 出处:网络
DateTime? billDateFrom = string.IsNullOrWhiteSpace开发者_Go百科(txtBillDateFrom.Text) ? null : (DateTime?)DateTime.Parse(txtBillDateFrom.Text);
DateTime? billDateFrom = string.IsNullOrWhiteSpace开发者_Go百科(txtBillDateFrom.Text) ? null : (DateTime?)DateTime.Parse(txtBillDateFrom.Text);

txtBillDateFrom.Text equals "05/26/2011". (26 may 2011)

This code throws an error "String was not recognized as a valid DateTime" only in a web application. In a console application it works good. Why? Does it depend on locale?


Yes, the behavior of Parse() depends on the current thread's culture. You can use ParseExact() to make that behavior consistent, regardless of that culture:

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


Yes it does. You can change thread's culture, or get a CultureInfo for a desired locale and pass its DateTimeFormat to 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);

Also I beleive you can set the culture in asp.net application's settings.

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


Yes, it depends on locale.

You can specify the locale that you want to use in the web.config file, or you can specify it in the call to Parse:`

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


It depends on current culture. In web.config you can set needed culture:

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


Try Below

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

精彩评论

暂无评论...
验证码 换一张
取 消