根据地区显示 Windows 10 UWP 应用程序的当前时间

Showing current time depending on region for Windows 10 UWP app

我认为这将是一个非常简单的问题,但我无法解决。在我的应用程序中,我想根据用户的区域设置显示当前时间。如果我的 phone 通常显示 17:48,我希望我的应用程序以这种格式显示它。如果它显示 5:48pm,那么同样的规则应该适用于我的应用程序。然而,无论我做什么,它只显示 am/pm 版本。我正在使用 System.DateTime class。我看到了一些可以这样做的解决方案(将时间设置为奥地利时间格式):

string time = DateTime.Now.ToString("t", de-AT);

而且有效! 但是,我不想手动设置它,而是根据用户 phone 设置使用区域格式。 我尝试使用 CultureInfo.CurrentCulture 获取语言国家/地区名称,如下所示:

string time = DateTime.Now.ToString("t", CultureInfo.CurrentCulture.Name);

这不起作用,因为 CultureInfo.CurrentCulture.Name 始终显示 en-US,即使我的 phone 设置为奥地利地区。 当我使用 GeographicRegion class 并打印时:

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

打印时我会得到字符串形式的 AT 和“Österreich”(= 奥地利)userRegion.NativeName;

有什么办法可以做到吗?

您可以使用

TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id);
DateTime dt = TimeZoneInfo.ConvertTime(DateTime.Now, timeZoneInfo);

经过几个小时的搜索,我找到了让它工作的方法!我使用 DateTimeFormatter class,它完全符合我的要求。至少据我所知。

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

        DateTimeFormatter timeFormatter = new DateTimeFormatter("hour minute", new[] { regionCode });
        string correctTime = timeFormatter.Format(DateTime.Now);           
        DateTimeFormatter dateFormatter = new DateTimeFormatter("dayofweek month day", new[] { regionCode });
        string correctDate = dateFormatter.Format(DateTime.Now);

如果有人发现其中有误并且它在所有地区都不起作用,请告诉我。