Convert country-specific date to UTC using NodaTime

I would like to convert a specific time value to UTC using NodaTime by specifying a country code.

For example, a country is Turkey, a country code is TR, and a specific time of February 5, 2016, 7:45 p.m. would be February 5, 2016 17:45, is this possible?

Also my location in the windows is not Turkey.

Are you in advance in advance?

+4
source share
1 answer

Well, you cannot do this only with the country code - you need a time zone. Some countries have several time zones.

Once you have a time zone like DateTimeZone(either through BCL TimeZoneInfoor the TZDB time zone provider), you should:

  • a LocalDateTime , , . LocalDateTimePattern
  • LocalDateTime.InZoneLeniently ( - ), ZonedDateTime
  • WithZone(DateTimeZone.Utc) UTC-based ZonedDateTime

InZoneLeniently, InZoneStrictly InZone(DateTimeZone, ZoneLocalMappingResolver) , , DST. . .

:

using System;
using NodaTime;
using NodaTime.Text;

class Test
{
    static void Main()
    {
        var text = "Feb 5, 2016 7:45 PM";
        var zone = DateTimeZoneProviders.Tzdb["Europe/Istanbul"];
        var pattern = LocalDateTimePattern.CreateWithInvariantCulture("MMM d, YYYY h:mm tt");
        var local = pattern.Parse(text).Value;
        var zoned = local.InZoneStrictly(zone);
        var utc = zoned.WithZone(DateTimeZone.Utc);
        Console.WriteLine(utc); // 2016-02-05T17:45:00 UTC (+00)
    }
}

, , TZDB (IANA) , Noda Time. , 2- ISO-3166, :

using NodaTime;
using NodaTime.TimeZones;
using System.Linq;
...
var code = "TR"; // Turkey
var zoneId = TzdbDateTimeZoneSource.Default.ZoneLocations
                                   .Single(loc => loc.CountryCode == code)
                                   .ZoneId;
var zone = DateTimeZoneProviders.Tzdb[zoneId];

Single , ( none).

, :

var zonesByCountryCode = TzdbDateTimeZoneSource.Default
   .ZoneLocations
   .GroupBy(loc => loc.CountryCode)
   .Where(g => g.Count() == 1) // Single-zone countries only
   .ToDictionary(g => g.Key, g => g.First());
+2

Source: https://habr.com/ru/post/1628129/


All Articles