繁体   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