WinRT apps and Regional settings. The correct way to format dates and numbers based on the user’s regional settings?

It’s been a while, but the question is not fully answered, so let me share my little research. Depechie is mostly right, but he provided only a link and wasn’t really sure.

Yes, this unexpected change is intentional. We shouldn’t use CultureInfo anymore as it contains legacy codes and Microsoft want us to use Windows.Globalization APIs instead.

To obtain current region we can use:

GeographicRegion userRegion = new GeographicRegion();
string regionCode = userRegion.CodeTwoLetter;

But as I noticed it contains only region information, there’s no language code. To obtain language we can use:

string langRegionCode = Windows.Globalization.Language.CurrentInputMethodLanguageTag; // depends on keyboard settings
List<string> langs = Windows.System.UserProfile.GlobalizationPreferences.Languages; // all user  languages, like in languages control panel
List<string> applicationlangs = Windows.Globalization.ApplicationLanguages.Languages; // application languages (user languages resolved against languages declared as supported by application)

They return BCP47 language tags in format language-REGION like “en-US” if language has dialects or just language like “pl” if the language doesn’t have major dialects.

We can also set one primary language which will override all the rest:

Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = "en-US";

(This is a persisted setting and is supposed to be used at user request)

There is also new API for date, time and numbers:

Windows.Globalization.DateTimeFormatting.DateTimeFormatter dtf = new DateTimeFormatter("longdate", new[] { "en-US" }, "US", CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour);
string longDate = dtf.Format(DateTime.Now);

Windows.Globalization.NumberFormatting.DecimalFormatter deciamlFormatter = new DecimalFormatter(new string[] { "PL" }, "PL");
double d1 = (double)deciamlFormatter.ParseDouble("2,5"); // ParseDouble returns double?, not double

There’s really a lot more in Windows.Globalization APIs, but I think that this gives us the general idea. For further reading:

You can also find some topics about the issue on windows 8 dev center forum with some Microsoft employee answers, but they mainly send you to the documentation.

Leave a Comment