Ben Aston
Ben Aston

Reputation: 55739

Determining if a UTC time is within DST

In C#, given a UTC time, how can I determine whether this falls within DST in Houston, Texas, US?

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


//bool fallsWithinDstInAmerica = ...?

Upvotes: 1

Views: 458

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500805

Get the appropriate TimeZoneInfo for Texas, then use 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
    }
}

Or using Noda Time, you can find the amount of daylight saving, and compare it with an offset of 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
    }
}

Upvotes: 5

Related Questions