.NET Get timezone offset by timezone name

37,541

Solution 1

You can use TimeZoneInfo.FindSystemTimeZoneById to get the TimeZoneInfo object using the supplied Id, then TimeZoneInfo.GetUtcOffset from that:

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
TimeSpan offset = tzi.GetUtcOffset( myDateTime);

Solution 2

You can use the TimeZoneInfo class's GetSystemTimeZones() method to fetch the list of all timezones configured on your server and match it to the one from your client.

Though why do you have timezones in the format "US Eastern Standard Time"? Where did that come from?

Solution 3

Rather than doing some manual addition you should take advantage of the ConvertTime method of TimeZoneInfo which will handle converting your date based on the TimeZone you specify.

var localizedDateTime = TimeZoneInfo.ConvertTime(yourDateTime, localTimeZoneInfo);
Share:
37,541
Daniil Harik
Author by

Daniil Harik

Hei,

Updated on January 16, 2020

Comments

  • Daniil Harik
    Daniil Harik over 4 years

    In database I store all date/times in UTC.

    I know user's timezone name ("US Eastern Standard Time" for example).

    In order to display correct time I was thinking that I need to add user's timezone offset to UTC date/time. But how would I get timezone offset by timezone name?

    Thank You!

  • Daniil Harik
    Daniil Harik almost 14 years
    Great idea, will try it now :) I'm populating one drop down with collection returned by GetSystemTimeZones()
  • ingredient_15939
    ingredient_15939 over 12 years
    This doesn't seem to work for me. Currently, it is DST in the zone "E. Australia Standard Time", so their time is GMT+11. However, when I run this I get a result of 10 hours. It should be 11. Code is: TimeZoneInfo.FindSystemTimeZoneById("E. Australia Standard Time").GetUtcOffset(Now.ToUniversalTime).Hours. What am I doing wrong?
  • Oded
    Oded over 12 years
    @ingredient_15939 - Possibly nothing wrong. Did you check that the computer this is running on is set to use DST correctly?
  • ingredient_15939
    ingredient_15939 over 12 years
    Thanks Oded. What do you mean by set to use it correctly? I'm actually coming across inconsistent results - I've just posted a question about it, please help if you can. stackoverflow.com/questions/8356866/…
  • Carlos P
    Carlos P almost 11 years
    Rather than populating the drop down with the Id/string of each TimeZone object in the collection, why not add the actual objects instead as Items in the drop down? That way, when the drop down is changed, you can just grab a reference to the TimeZoneInfo object using (TimeZoneInfo)myDropDown.SelectedItem Then you wouldn't need to call .FindSystemTimeZoneById each time, you'd already have the object.
  • Shiv
    Shiv over 3 years
    @ingredient_15939 you are specifying E Australian Standard Time which is ALWAYS +10. E Australian Daylight Saving Time is +11.