【问题标题】:Date to UTC not taking into account daylight savingsUTC 日期不考虑夏令时
【发布时间】:2018-02-04 08:34:54
【问题描述】:

我正在使用带有时区(东部标准时间)的日期(2018 年 1 月 1 日上午 11:30)并将其转换为 UTC 日期(2018-01-01T16:30:00Z)。原始日期实际上是东部夏令时,因此当开发人员使用 UTC 进行转换时,他们会得到 12:30 PM 而不是 11:30 AM。如果我在 2018 年 8 月 26 日上午 11:30 做,它工作正常。我的时区采用 .NET Windows 格式。

我下面的方法有没有办法从 NodaTime 标准时区获取具有夏令时的正确 UTC?

2018-01-01T16:30:00Z = Helper.GetUtcTimeZone("1/1/2018 11:30 AM", "Eastern Standard Time").ToString();

方法

public static Instant GetUtcTimeZone(DateTime dateTime, string timeZone)
{
    var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone ?? TimeZoneInfo.Local.StandardName);

    if (timeZoneInfo != null)
    {
        if (dateTime.Kind == DateTimeKind.Unspecified)
        {
            dateTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZoneInfo);
        }
    }

    return Instant.FromDateTimeUtc(dateTime);
}

【问题讨论】:

    标签: .net datetime timezone dst nodatime


    【解决方案1】:

    如果你想继续使用TimeZoneInfo,直接使用即可。不需要您添加的所有额外逻辑。

    public static Instant GetUtcTimeZone(DateTime dateTime, string timeZone)
    {
        TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
        DateTime utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZoneInfo);
        return Instant.FromDateTimeUtc(utcDateTime);
    }
    

    虽然真的,一旦您使用了 NodaTime,就没有理由这样做了。只需使用它的内置功能:

    public static Instant GetUtcTimeZone(DateTime dateTime, string timeZone)
    {
        LocalDateTime ldt = LocalDateTime.FromDateTime(dateTime);
        DateTimeZone tz = DateTimeZoneProviders.Bcl[timeZone];
        return ldt.InZoneLeniently(tz).ToInstant();
    }
    

    一个重要的提示:你有一个回退到TimeZoneInfo.Local.StandardName。这是不安全的 - 因为StandardName 字段是本地化的,即使是英文也不总是匹配标识符的名称。如果您需要标识符,请使用 Id 而不是 StandardName。在 NodaTime 中,您可以使用DateTimeZoneProviders.Bcl.GetSystemDefault()

    【讨论】:

    • 另请注意,您给出的第一个日期是 1 月,所以它不能在 EDT。
    猜你喜欢
    • 2014-06-01
    • 2021-01-21
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 2018-01-01
    • 2012-05-01
    • 2012-09-08
    相关资源
    最近更新 更多