Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do DateTimeOffset.Now.Offset and TimeZoneInfo.Local.BaseUtcOffset return different values?

Tags:

c#

datetime

I am currently in the UTC -6 Central Time zone. TimeZoneInfo.Local.BaseUtcOffset returns -6, but DateTimeOffset.Now.Offset returns -5. I am at a loss as to why these would be different, and I can find no documentation that would explain this. Does one respect daylight savings time and the other does not? If I perform someDateTimeOffset.UtcDateTime.ToLocalTme(), I get a DateTime offset by -6 hours as well.

like image 239
Matt H Avatar asked Sep 20 '12 20:09

Matt H


1 Answers

As per the documentation for TimeZoneInfo.BaseUtcOffset:

An object that indicates the time difference between the current time zone's standard time and Coordinated Universal Time (UTC).

and

Because BaseUtcOffset is a property of the TimeZoneInfo object rather than the TimeZoneInfo.AdjustmentRule object, the TimeZoneInfo class applies a single offset from UTC to all of a time zone's adjustments.

Whereas DateTimeOffset.Now.Offset returns the different between the current time in the local time zone and UTC. Not the current time zone's standard time. Central Time is observing daylight saving time at the moment, hence the discrepancy.

The documentation also gives you guidance about what to use if you want to get the offset at any particular time from a TimeZoneInfo:

The BaseUtcOffset property returns the difference between UTC and the time zone's standard time; the GetUtcOffset method returns the difference between UTC and the time zone's time at a particular point in time.

If I perform someDateTimeOffset.UtcDateTime.ToLocalTme(), I get a DateTime offset by -6 hours as well.

Well that will depend on exactly what value someDateTimeOffset has. For example, if it's in winter time, you'd see a 6 hour offset, sure.

like image 96
Jon Skeet Avatar answered Nov 01 '22 23:11

Jon Skeet