微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;
}

原文地址:https://www.jb51.cc/csharp/244171.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐