2017-04-19

Get time for given country

This code gets the first time zone for a country (meaning it probably won't work if your country has more than one), and calculates the date/time given the UTC date/time.

The method is an extension to the DateTime type, meaning you can use it by typing .AsLocalTimeForGivenCountryFromUtc(countryCode) after a variable or function returning that type. The countryCode parameter is a string, and must be a two-letter ISO 3166-1 country code.

You need to import John Skeets NodaTime library from NuGet.

Code:
using NodaTime.TimeZones;
using System;
using System.Linq;

namespace MyNameSpace
{

    public static class DateTimeExtension
    {

        public static DateTime AsLocalTimeForGivenCountryFromUtc(this DateTime utcDateTime, string countryCode)
        {
            //no matter what tz info is on the date, assume it is UTC
            var dte = new DateTime(utcDateTime.Year, utcDateTime.Month, utcDateTime.Day, utcDateTime.Hour, utcDateTime.Minute, utcDateTime.Second, DateTimeKind.Utc);
            var tzMapping = TzdbDateTimeZoneSource.Default.WindowsMapping.MapZones.FirstOrDefault(t => t.Territory == countryCode); //NodaTime
            var tz = TimeZoneInfo.FindSystemTimeZoneById(tzMapping.WindowsId);
            return TimeZoneInfo.ConvertTimeFromUtc(dte, tz);
        }
    }
}

No comments:

Post a Comment