简体   繁体   English

如何从TimeZoneInfo获取国家名称

[英]How to get country name from TimeZoneInfo

If we have TimeZoneInfo how can we get country name for the selected Timezone. 如果我们有TimeZoneInfo ,我们如何获得所选时区的国家/地区名称。

Example: 例:

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

Thank you 谢谢

I see no built in way to do it. 我认为没有内置的方法可以做到这一点。 TimeZoneInfo class does not have a property or a method which returns a country code. TimeZoneInfo类没有返回国家代码的属性或方法。 See: https://docs.microsoft.com/en-us/dotnet/api/system.timezoneinfo?view=netframework-4.7.2 请参阅: https : //docs.microsoft.com/zh-cn/dotnet/api/system.timezoneinfo?view=netframework-4.7.2

The behaviour of TimeZoneInfo is also dependent on the Operating Systems it runs on. TimeZoneInfo的行为还取决于其运行的操作系统。 See below: 见下文:

Running the following code on NET Core 2.1 on Windows 10: 在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);

Gives output: 给出输出:

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.

Running the same code NET Core 2.1 on macOS High Sierra: 在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.

The closest approximation you can implement is: 您可以实现的最接近的近似值是:

  1. Download a recent copy of tz database. 下载tz数据库的最新副本。 You can use https://en.wikipedia.org/wiki/List_of_tz_database_time_zones 您可以使用https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

  2. Download a copy of country codes. 下载国家代码副本。 Wikipedia has a list: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Wikipedia有一个列表: https : //en.wikipedia.org/wiki/ISO_3166-1_alpha-2

  3. Implement code that searches your TZ database by TZ name like "Europe/Budapest". 实现以TZ名称(例如“欧洲/布达佩斯”)搜索TZ数据库的代码。 This gives you a Country Code. 这给您一个国家代码。 Then search your Country Database with the two letter country code which will get you a Country Name. 然后,用两个字母的国家代码搜索您的国家数据库,这将为您提供一个国家名称。

This method is not cross platform! 这种方法不是跨平台的! And your application must be updated when the tz database of the list of country codes changes. 国家代码列表的tz数据库更改时,您的应用程序必须更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM