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:
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:
Since .NET 3.5, you can use the following from DateTimeOffset
to get the current offset.
var offset = DateTimeOffset.Now.Offset;
MSDN documentation