'Get Timezone Offset of Server in C#

How can I get the timezone offset of the physical server running my code? Not some date object or other object in memory.

For example, the following code will output -4:00:00:

<%= TimeZone.CurrentTimeZone.GetUtcOffset(new DateTime()) %>

When it should be -03:00:00 because of daylight savings



Solution 1:[1]

new DateTime() will give you January 1st 0001, rather than the current date/time. I suspect you want the current UTC offset... and that's why you're not seeing the daylight saving offset in your current code.

I'd use TimeZoneInfo.Local instead of TimeZone.CurrentTimeZone - it may not affect things, but it would definitely be a better approach. TimeZoneInfo should pretty much replace TimeZone in all code. Then you can use GetUtcOffset:

var offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);

(Using DateTime.Now should work as well, but it involves some magic behind the scenes when there are daylight saving transitions around now. DateTime actually has four kinds rather than the advertised three, but it's simpler just to avoid the issue entirely by using UtcNow.)

Or of course you could use my Noda Time library instead of all this BCL rubbish ;) (If you're doing a lot of date/time work I'd thoroughly recommend that - obviously - but if you're only doing this one bit, it would probably be overkill.)

Solution 2:[2]

Since .NET 3.5, you can use the following from DateTimeOffset to get the current offset.

var offset = DateTimeOffset.Now.Offset;

MSDN documentation

Solution 3:[3]

There seems to be some difference between how GetUtcOffset works with new DateTime() and DateTime.Now. When I run it in the Central Time Zone, I get:

TimeZone.CurrentTimeZone.GetUtcOffset(new DateTime()) // -06:00:00

TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now)   // -05:00:00

It's a bit of a kludge, but I suppose you could also do this:

DateTime.Now - DateTime.UtcNow // -05:00:00

Solution 4:[4]

A quick-and-dirty way to get the current time zone offset is to subtract UTC time from local time:

DateTime CurrentTime = DateTime.Now;
TimeSpan CurrentOffset = CurrentTime - CurrentTime.ToUniversalTime();

Here in Alaska this currently returns a TimeSpan of -08:00:00.

You can then instantiate a new DateTimeOffset object:

DateTimeOffset CurrentDto = new DateTimeOffset(CurrentTime, CurrentOffset);

Solution 5:[5]

When you contract a new DateTime object it gets DateTime.MinValue When you get its TimeZone.CurrentTimeZone.GetUtcOffset you actually get the time offset for that date.

If you use the DateTime.Now you will get the current date & time and therefore the current offset.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew
Solution 2 Kasey Speakman
Solution 3
Solution 4
Solution 5 InteXX