簡體   English   中英

WinRT-如何根據用戶區域性獲取正確的DateTimeFormatter

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

我很難為用戶找到合適的DateTimeFormatter。

例如,將日期轉換為字符串時

.ToString("D");

在WinRT中始終使用美國文化。

我發現應該使用新的全球化API。

例如

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

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


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

但HomeGeographicRegion的結果格式不符合新的DateTimeformatter要求

我也試過了

 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);

但這也只會返回en-Us格式的日期字符串。

誰能告訴我根據用戶文化(它也通過uid自動用於資源本地化)獲取DateTimeFormatter的正確方法是什么?

單個參數DateTimeFormatter構造函數采用一個模板(類似於“ month.abbreviated day dayofweek”)。 為此提供區域將失敗,並帶有無效的參數。

對於Windows Store應用程序,構造沒有日期參數的DateTimeFormatters等效於DateTimeFormatter是通過提供Windows.Globalization.ApplicationLanguages.Languages屬性的值構造的。 對於桌面應用程序,默認值為用戶區域設置。

請注意,應用程序語言是從用戶語言(可以在Windows.System.UserProfile.GlobalizationPreferences.Languages上查詢)和已聲明的應用程序清單語言(可以在Windows.Globalization.ApplicationLanguages.ManifestLanguages上查詢)解析的。

最后, ResolvedLanguage屬性將使您確切地看到DateTimeFormatter內部使用的是哪種語言。

以我的經驗,當人們獲得意料之外的結果時,通常是因為該應用程序僅支持一種語言,在這種情況下,無論用戶的喜好如何,應用程序語言始終都是。 否則,請驗證您期望的語言是否在用戶語言列表的頂部。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM