简体   繁体   中英

How to get country using IANA timezone or timezone object in C#

I'm trying to get the country from one of the following ways. I have timezone, timezone id and timezone info given below. If this is possible to get the country, please help me out.

IANA result: Asia/Kolkata
windows: India Standard Time
TimeZoneInfo: {(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi}

result: IND India

My Noda Time project can provide the location information that is in the IANA database, if there is any. Here's some sample code, using the default IANA database that's embedded in Noda Time. You can also load a specific version of the data from an NZD file - we provide new NZD files every time there's a new IANA data release.

using NodaTime.TimeZones;
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        DisplayCountryInfo("Europe/London");
        DisplayCountryInfo("Asia/Kolkata");
    }

    static void DisplayCountryInfo(string id)
    {
        var source = TzdbDateTimeZoneSource.Default;
        Console.WriteLine($"ID: {id}");
        if (!source.GetIds().Contains(id))
        {
            Console.WriteLine("ID not found. Aborting");
            Console.WriteLine();
            return;
        }

        var canonicalId = source.CanonicalIdMap[id];
        Console.WriteLine($"Canonical ID: {canonicalId}");
        var location = source.ZoneLocations.FirstOrDefault(loc => loc.ZoneId == canonicalId);
        if (location is null)
        {
            Console.WriteLine($"No location found.");
        }
        else
        {
            Console.WriteLine($"Country: {location.CountryName}");
            Console.WriteLine($"Code: {location.CountryCode}");
        }
        Console.WriteLine();
    }
}

Output:

ID: Europe/London
Canonical ID: Europe/London
Country: Britain (UK)
Code: GB

ID: Asia/Kolkata
Canonical ID: Asia/Kolkata
Country: India
Code: IN

Note that the code is "IN" rather than "IND"; "IN" is the ISO-3166 country code for India.

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