首页 > 解决方案 > 如何从 TimeZoneInfo 获取国家名称

问题描述

如果我们有我们TimeZoneInfo如何获得所选时区的国家名称。

例子:

Asia/Singapore = Singapore
Asia/Tokyo     = Tokyo
Europe/Moscow  = Russia

谢谢

标签: c#timezone

解决方案


我认为没有内置的方法可以做到这一点。TimeZoneInfo 类没有返回国家代码的属性或方法。请参阅:https ://docs.microsoft.com/en-us/dotnet/api/system.timezoneinfo?view=netframework-4.7.2

TimeZoneInfo 的行为也取决于它运行的操作系统。见下文:

在 Windows 10 上的 NET Core 2.1 上运行以下代码:

TimeZoneInfo localZone = TimeZoneInfo.Local;
Console.WriteLine("Local Time Zone ID: {0}", localZone.Id);
Console.WriteLine("   Display Name is: {0}.", localZone.DisplayName);
Console.WriteLine("   Standard name is: {0}.", localZone.StandardName);
Console.WriteLine("   Daylight saving name is: {0}.", localZone.DaylightName);

给出输出:

Local Time Zone ID: Central Europe Standard Time
Display Name is: (UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague.
Standard name is: Central Europe Standard Time.
Daylight saving name is: Central Europe Summer Time.

在 macOS High Sierra 上运行相同的代码 NET Core 2.1:

Local Time Zone ID: Europe/Budapest
Display Name is: GMT+01:00.
Standard name is: GMT+01:00.
Daylight saving name is: GMT+02:00.

您可以实现的最接近的近似值是:

  1. 下载 tz 数据库的最新副本。您可以使用https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

  2. 下载国家代码的副本。维基百科有一个列表:https ://en.wikipedia.org/wiki/ISO_3166-1_alpha-2

  3. 实现通过 TZ 名称搜索 TZ 数据库的代码,例如“Europe/Budapest”。这会给你一个国家代码。然后使用两个字母的国家代码搜索您的国家数据库,这将为您提供一个国家名称。

此方法不跨平台!当国家代码列表的 tz 数据库发生变化时,您的应用程序必须更新。


推荐阅读