简体   繁体   中英

DateTime.TryParse fails for one user

I need to parse dates in my program, but it fails on the machine of one user (in denmark). It works for his colleagues who all has the same settings as far as I can tell.

The code looks as follows:

DateTime result;
if (DateTime.TryParse(InputBox.Text, out result))
    YyyymmddField.Text = result.ToString("yyyyMMdd");
else
    YyyymmddField.Text = "(invalid)";

CurrentCulture is da-DK and his configured format is: yyyy.MM.dd . The date string I want to parse is 2015.07.14 . This works on our machines here (in sweden) regardless of current culture. It also works for his colleagues, but not for him.

We have hundreds of users worldwide and as far as we know, his is the only computer that fails.

Could something other than the current CultureInfo affect how TryParse operates?

This works on our machines here (in sweden) regardless of current culture

No. There is no such a thing. If you use DateTime.TryParse without any IFormatProvider , it will use the CurrentCulture settings of the current machine.

From documentation ;

The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture.

I'm using .NET Framework 4.5 and there are only 7 culture inside of AllCultures that doesn't have this as standard date and time format. If you won't/can't tell us what is your other colleague's CurrentCulture , I would assume he will use one of these from my perspective.

ar
bn
ml
ar-SA
bn-IN
ml-IN
bn-BD

Instead of that confusion, you can use InvariantCulture is your string has a stable format like yyyy.MM.dd instead of hoping his CurrentCulture settings will parse it or not.

use CultureInfo.InvariantCulture

DateTime result;
    if (DateTime.TryParse(InputBox.Text, out result))
        YyyymmddField.Text = result.ToString("yyyyMMdd",CultureInfo.InvariantCulture);
    else
        YyyymmddField.Text = "(invalid)";

原则上,使用可重用的方法(例如扩展方法)来解析使用不变文化的DateTimes和数字是一个好主意。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM