简体   繁体   中英

How to get country name from TimeZoneInfo

If we have TimeZoneInfo how can we get country name for the selected Timezone.

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. See: https://docs.microsoft.com/en-us/dotnet/api/system.timezoneinfo?view=netframework-4.7.2

The behaviour of TimeZoneInfo is also dependent on the Operating Systems it runs on. See below:

Running the following code on NET Core 2.1 on Windows 10:

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:

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. You can use 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

  3. Implement code that searches your TZ database by TZ name like "Europe/Budapest". 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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