Current Time of Timezone

前端 未结 3 1785
情书的邮戳
情书的邮戳 2021-01-18 08:57

I have different timezones and their GMT and DST. Example:

TimeZoneId        |   GMT offset  |   DST offset  
              


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 09:27

    The time zone IDs you've given are the ones from the IANA time zone database, aka TZDB (aka Olson, aka tz). They're not supported by .NET (although .NET Core running on Linux/Mac will probably do what you want).

    My Noda Time project does support them though. You'd use:

    var zoneId = "America/Antigua";
    var zone = DateTimeZoneProviders.Tzdb[zoneId];
    var now = SystemClock.Instance.GetCurrentInstant();
    var zoned = now.InZone(zone);
    Console.WriteLine(zoned);
    

    That uses the SystemClock explicitly - in real code I'd advise you to accept an IClock via dependency injection for testability - inject SystemClock.Instance when running the application, but use FakeClock for testing.

    Alternative equivalent code demonstrating ZonedClock:

    var zoneId = "America/Antigua";
    var zone = DateTimeZoneProviders.Tzdb[zoneId];
    var systemClock = SystemClock.Instance;
    var zonedClock = systemClock.InZone(zone);
    var zoned = zonedClock.GetCurrentZonedDateTime();
    Console.WriteLine(zoned);
    

提交回复
热议问题