确定UTC时间是否在DST范围内

时间:2013-09-20 11:56:09

标签: c# date time timezone

在C#中,给定一个UTC时间,如何确定这是否属于美国德克萨斯州休斯顿的DST?

var utcDateTime = new DateTime(2013,1,1,0,0,0,DateTimeKind.Utc);


//bool fallsWithinDstInAmerica = ...?

1 个答案:

答案 0 :(得分:5)

为德克萨斯州获取适当的TimeZoneInfo,然后使用IsDaylightSavingTime

using System;

class Test
{
    static void Main()
    {
        // Don't be fooled by the "standard" part - this is Central Time
        var zone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
        var winter = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        var summer = new DateTime(2013, 6, 1, 0, 0, 0, DateTimeKind.Utc);
        Console.WriteLine(zone.IsDaylightSavingTime(winter)); // False
        Console.WriteLine(zone.IsDaylightSavingTime(summer)); // True
    }
}

或者使用Noda Time,您可以找到夏令时的数量,并将其与偏移量0进行比较:

using System;
using NodaTime;

class Test
{
    static void Main()
    {
        var zone = DateTimeZoneProviders.Tzdb["America/Chicago"];
        var winter = Instant.FromUtc(2013, 1, 1, 0, 0);
        var summer = Instant.FromUtc(2013, 6, 1, 0, 0);

        Console.WriteLine(zone.GetZoneInterval(winter).Savings); // +00
        Console.WriteLine(zone.GetZoneInterval(summer).Savings); // +01
        Console.WriteLine(zone.GetZoneInterval(winter).Savings != Offset.Zero); // False
        Console.WriteLine(zone.GetZoneInterval(summer).Savings != Offset.Zero); // True
    }
}