简体   繁体   中英

WinRT - How To Get the correct DateTimeFormatter based on the user culture

I've some trouble finding the right DateTimeFormatter for the user.

When converting a date to a string for example with

.ToString("D");

always the en-US culture is used in WinRT.

I found out that there are new globalization apis which should be used.

for example

       var langs = Windows.System.UserProfile.GlobalizationPreferences.Languages;

       var homeregion = Windows.System.UserProfile.GlobalizationPreferences.HomeGeographicRegion;


           Windows.Globalization.DateTimeFormatting.DateTimeFormatter dtf = new DateTimeFormatter(homeregion);

but the result of HomeGeographicRegion is not in the format with a new DateTimeformatter requires

I also tried this

 var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter(Windows.Globalization.DateTimeFormatting.YearFormat.Default,
                Windows.Globalization.DateTimeFormatting.MonthFormat.Abbreviated,
                Windows.Globalization.DateTimeFormatting.DayFormat.Default,
                Windows.Globalization.DateTimeFormatting.DayOfWeekFormat.Default);

                string result = formatter.Format(Date);

but that also only returns date string in en-Us format.

Can anyour tell me what is the correct way to get a DateTimeFormatter according to the users culture (which is also automatically used for resource localizations via uid)?

The single argument DateTimeFormatter constructor takes a template (something like "month.abbreviated day dayofweek"). Providing a region to this will fail with an invalid argument.

For Windows Store applications, the DateTimeFormatters constructed without a languages parameter, will be equivalent to if the DateTimeFormatter had been constructed by providing the value of the Windows.Globalization.ApplicationLanguages.Languages property . For desktop applications, the default is the user locale.

Note that the application languages are resolved from the user languages (which you can query at Windows.System.UserProfile.GlobalizationPreferences.Languages) and the declared application manifest languages (which you can query at Windows.Globalization.ApplicationLanguages.ManifestLanguages ).

Finally, the ResolvedLanguage property will let you see exactly what language is being used internally by the DateTimeFormatter.

In my experience, when people get results that they didn't expect, it is generally because the application only supports a single language, in which case, the application language will always be that no matter what the user preference is. Otherwise, verify that the language you expect is at the top of your user language list.

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