Pawan Nogariya
Pawan Nogariya

Reputation: 8960

Getting wrong UTC offset hours for exact daylight date

I am trying to get the offset hours of a particular time for EST timezone like this

var est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
est.GetUtcOffset(new DateTime(2020, 3, 9)).Hours;

This works fine and returns me -4, which is right for 9th March 2020 because the daylight saving changes on 8th March 2020 02:00:00, but when I try to run the same code for date 8th March 2020 02:00:00, it returns me -5, while my understanding is that from 2am of 8th march it should start returning me -4.

To get the -4, I have to run it for 3am, that is one hour after the daylight changing.

But why is it so? Why do I have to add one hour to make daylight change take effect?

Upvotes: 3

Views: 563

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241555

From the Remarks section of the TimeZoneInfo.GetUtcOffset docs:

... If dateTime is ambiguous, or if the converted time is ambiguous, this method interprets the ambiguous time as a standard time. If dateTime is invalid, this method returns a TimeSpan object that reflects the difference between UTC and the time zone's standard time.

The datetime 2020-03-08 02:00:00, is invalid in the US Eastern time zone, because the clocks advance from 01:59:59 to 03:00:00 on that day. Thus, the GetUtcOffset uses its described behavior of returning the standard time offset. You can detect this if you first call TimeZoneInfo.IsInvalidTime.

You might want to also use other methods from TimeZoneInfo to apply specific behavior. For example, it's commonly desired in appointment scheduling scenarios to use the behavior I presented in the ToDateTimeOffset extension method in this other answer.

Upvotes: 1

Related Questions