Oliver Nilsen
Oliver Nilsen

Reputation: 1273

Map an address to a Windows Timezone

I am looking into mapping a location such as an adress to a Windows TimeZone format. For instance if the address contains the Copenhagen city, then the service should map it to (UTC+01:00) Brussels, Copenhagen, Madrid, Paris.

If the address contains a city close to Vienna then it should map it to (UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna.

I have looked into Google's GeoCoding and TimeZone APIs, but it only gives me the name of the timezone like "Central European Time".

Upvotes: 0

Views: 483

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241475

This is a multi-step process:

  1. Determine the location's latitude and longitude coordinates.

    • You mentioned Google's geocoding API. That will do fine, and there are several others to choose from.
  2. Determine the time zone identifier from those coordinates using any of these methods.

    • In most cases, you'll receive an IANA time zone identifier, such as "Europe/Vienna". You mentioned the Google time zone API - which returns this value in the timeZoneId field (not timeZoneName).
  3. Use the IANA time zone identifier to obtain a .NET TimeZoneInfo object.

    • If you are running .NET on a non-Windows platform (Linux, OSX, etc.) you can obtain a TimeZoneInfo object directly from the IANA time zone identifier:

      // This will work on platforms that use IANA time zones natively
      TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Europe/Vienna");
      
    • If you are running .NET on Windows, or want to write your application to run on any platform, then use my TimeZoneConverter library to retrieve the TimeZoneInfo object:

      // This will work on any platform
      TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Europe/Vienna");
      

If you actually need a Windows time zone identifier, then TimeZoneConverter can do that as well:

string tz = TZConvert.IanaToWindows("Europe/Vienna");
//=> "W. Europe Standard Time"

Separately, if you want to get the actual string "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", then:

  • If on Windows, and the Windows OS locale is English, then you can just get .DisplayName from the TimeZoneInfo object.

  • In all other cases, you can skip step 3 above and just use my TimeZoneNames library, which has all display names for all languages:

    string displayName = TZNames.GetDisplayNameForTimeZone("Europe/Vienna", "en");
    

Also, you might consider using NodaTime instead of a TimeZoneInfo object.

Upvotes: 1

Related Questions