Formatting/parsing for a specific culture redux

Formatting/parsing for a specific culture redux

In recent blog post I detailed how creating a culture via the CultureInfo constructor could actually create a user-overridden culture–which could be completely different than the culture that you’ve requested by name. Fortunately there’s a way of overriding the user override (apologies for overloading “override”) by supplying the boolean value “false” in a CultureInfo overload.

In case you’re wondering why this is more serious, consider the following following block of code that formats a date value as text:

System.Globalization.CultureInfo ci;

String text;

ci = System.Globalization.CultureInfo.CreateSpecificCulture(“en-us”);

text = String.Format(ci, “{0:d}”, DateTime.Now);

And that text is transmitted to another application (or another session of the same application, e.g. serialization), potentially in another locale, to be parsed with the following block of code:

System.Globalization.CultureInfo ci;

ci = System.Globalization.CultureInfo.CreateSpecificCulture(“en-us”);

String text = ReadRecord();

DateTime now = DateTime.Parse(text, ci);

If either (or) the user’s current culture is set to “English (United States)” and they’ve overridden the currency format the short date (say from “M/d/yyyy” to “d/M/yyyy”) will randomly result in the wrong date.