Converting between time zones with Noda Time

ε祈祈猫儿з 提交于 2019-12-03 05:10:18
Jon Skeet

Your first method looks okay, although we don't know what customResolver is.

Your second method is a bit off. I'd suggest:

public static DateTime ConvertToEasternTimeZoneFromUtc(DateTime utcDateTime)
{
    var easternTimeZone = DateTimeZoneProviders.Tzdb["America/New_York"];
    return Instant.FromDateTimeUtc(utcDateTime)
                  .InZone(easternTimeZone)
                  .ToDateTimeUnspecified();
}

Note that you don't need to look up the Eastern time zone in every method call - just have:

private static readonly DateTimeZone EasternTimeZone = 
    DateTimeZoneProviders.Tzdb["America/New_York"];

... then use that everywhere.

Your third and fourth methods aren't what I'd think of as idiomatic - for the third method you should use:

public static DateTime ConvertToUtc(DateTime dateTime, int offsetInMinutes)
{
    var offset = Offset.FromMinutes(offsetInMinutes);
    var localDateTime = LocalDateTime.FromDateTime(dateTime);
    return new OffsetDateTime(localDateTime, offset).ToInstant()
                                                    .ToDateTimeUtc();
}

The fourth method seems a bit trickier, as we don't provide everything we should in terms of conversions with OffsetDateTime. The code you've used is probably okay, but it would certainly be cleaner if you could use OffsetDateTime.

EDIT: I've now added a method to Instant to make the fourth method cleaner. It will be part of 1.2.0, and you can use:

public static DateTime ConvertFromUtc(DateTime dateTime, int offsetInMinutes)
{
    var offset = Offset.FromMinutes(offsetInMinutes);
    var instant = Instant.FromDateTimeUtc(dateTime);
    return instant.WithOffset(offset)
                  .LocalDateTime
                  .ToDateTimeUnspecified();
}

I would like to add that the first method could be rewritten without customResolver.

using System;
using NodaTime;

namespace qwerty
{
    class Program
    {
        static void Main(string[] args)
        {
            var convertedInUTC = ConvertToUtcFromCustomTimeZone("America/Chihuahua", DateTime.Now);
            Console.WriteLine(convertedInUTC);
        }

        private static DateTime ConvertToUtcFromCustomTimeZone(string timezone, DateTime datetime) 
        {
            DateTimeZone zone = DateTimeZoneProviders.Tzdb[timezone];
            var localtime = LocalDateTime.FromDateTime(datetime);
            var zonedtime = localtime.InZoneLeniently(zone);
            return zonedtime.ToInstant().InZone(zone).ToDateTimeUtc();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!