c# – 这是在Nodatime中转换时区的正确方法吗?

目标是创建一个函数,使用Nodatime将时间从一个时区转换为另一个时区.我不只是在寻找关于结果是否正确的反馈,而是针对“我如何”这样做的反馈(这是真的正确,还是有微妙的漏洞).

这是功能

static zoneddatetime ConvertDateTimetoDifferentTimeZone(DateTime p_from_datetime,string p_from_zone,string p_to_zone)
{
    DateTimeZone from_zone = DateTimeZoneProviders.Tzdb[p_from_zone];
    LocalDateTime from_local = new LocalDateTime(p_from_datetime.Year,p_from_datetime.Month,p_from_datetime.Day,p_from_datetime.Hour,p_from_datetime.Minute);
    zoneddatetime from_datetime = from_zone.AtStrictly(from_local);

    var from_instant = from_datetime.ToInstant();

    DateTimeZone to_zone = DateTimeZoneProviders.Tzdb[p_to_zone];
    zoneddatetime to_datetime = to_zone.AtStrictly(from_local);

    var to_offset_datetime = from_instant.WithOffset(to_datetime.Offset);

    return to_zone.AtStrictly(to_offset_datetime.LocalDateTime);
}

我称之为的方式如下:

DateTime from_datetime = new DateTime(2016,10,15,16,30,0);
    string from_zone = "US/Central";
    string to_zone = "US/Eastern";
    var x = ConvertDateTimetoDifferentTimeZone(from_datetime,from_zone,to_zone);

    Console.WriteLine(from_datetime.ToString() + " (" + from_zone + ") = " + " (" + x.ToString() + " (" + to_zone + ")");

我错过了什么或做错了吗?

解决方法

我会尽可能坚持Noda Time类型(和.NET命名约定).区域之间的转换应该用 ZonedDateTime.WithZone完成 – 这意味着你真的要求转换为zoneddatetime和从zoneddatetime转换.如果你真的,真的必须使用DateTime而不是Noda Time类型,你可能想要这样的东西:
public static DateTime ConvertDateTimetoDifferentTimeZone(
    DateTime fromDateTime,string fromZoneId,string tozoneId)
{
    LocalDateTime fromLocal = LocalDateTime.FromDateTime(fromDateTime);
    DateTimeZone fromZone = DateTimeZoneProviders.Tzdb[fromZoneId];
    zoneddatetime fromZoned = fromLocal.InZoneLeniently(fromZone);

    DateTimeZone toZone = DateTimeZoneProviders.Tzdb[toZoneId];
    zoneddatetime toZoned = fromZoned.WithZone(toZone);
    LocalDateTime toLocal = toZoned.LocalDateTime;
    return toLocal.ToDateTimeUnspecified();
}

注意这里使用InZoneLeniently – 这意味着如果由于UTC偏移的跳跃(通常由于夏令时)而给出的本地时间无效,它仍然会返回一个值而不是抛出异常 – 请参阅文档更多细节.

如果你在整个过程中使用Noda Time,很难知道这个方法是什么样的,因为我们不知道你是从一个LocalDateTime还是一个zoneddatetime开始.例如,您可以:

public static LocalDateTime ConvertDateTimetoDifferentTimeZone(
    LocalDateTime fromLocal,string tozoneId)
{
    DateTimeZone fromZone = DateTimeZoneProviders.Tzdb[fromZoneId];
    zoneddatetime fromZoned = fromLocal.InZoneLeniently(fromZone);

    DateTimeZone toZone = DateTimeZoneProviders.Tzdb[toZoneId];
    zoneddatetime toZoned = fromZoned.WithZone(fromZone);
    return toZoned.LocalDateTime;
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...