【问题标题】:WinRT - How To Get the correct DateTimeFormatter based on the user cultureWinRT - 如何根据用户文化获取正确的 DateTimeFormatter
【发布时间】:2013-02-23 12:12:13
【问题描述】:

我在为用户找到正确的 DateTimeFormatter 时遇到了一些麻烦。

例如使用

将日期转换为字符串时
.ToString("D");

在 WinRT 中始终使用 en-US 区域性。

我发现应该使用新的全球化 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 格式的日期字符串。

你能告诉我根据用户文化获取 DateTimeFormatter 的正确方法是什么(也通过 uid 自动用于资源本地化)?

【问题讨论】:

  • ToString(String) 使用“当前”文化。你是说如果你改成 en-us 以外的东西,ToString 仍然格式化为 en-us?
  • 嗯,我没有改变它,但我希望文化是 de-DE,因为它是一台没有任何额外语言的德国电脑。但你的权利,文化是我们。那么为什么winrt不尊重这一点并将其设置为文化呢?所以我需要以其他方式获得用户文化?

标签: c# windows-runtime globalization culture


【解决方案1】:

单个参数DateTimeFormatter constructor 采用模板(类似于“month.abbrevied day dayofweek”)。为其提供区域将失败并返回无效参数。

对于 Windows 应用商店应用程序,不带语言参数构造的 DateTimeFormatter 将等效于通过提供 Windows.Globalization.ApplicationLanguages.Languages property 的值构造 DateTimeFormatter。对于桌面应用程序,默认为用户区域设置。

请注意,应用程序语言是从用户语言(您可以在 Windows.System.UserProfile.GlobalizationPreferences.Languages 查询)和声明的应用程序清单语言(您可以在 Windows.Globalization.ApplicationLanguages.ManifestLanguages 查询)解析的。

最后,ResolvedLanguage property 将让您准确了解 DateTimeFormatter 内部使用的语言。

根据我的经验,当人们得到意想不到的结果时,通常是因为应用程序只支持一种语言,在这种情况下,无论用户偏好是什么,应用程序语言都将始终是那个。否则,请确认您期望的语言位于用户语言列表的顶部。

【讨论】:

  • 那是缺失的部分。用户 lang 是 de-de 和 en-gb,但清单中只有 en-us,所以应用程序文化是 en-gb,这对我来说似乎是合乎逻辑的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多