.NET Get timezone offset by timezone name
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);
Comments
-
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 almost 14 yearsGreat idea, will try it now :) I'm populating one drop down with collection returned by GetSystemTimeZones()
-
ingredient_15939 over 12 yearsThis 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 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 over 12 yearsThanks 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 almost 11 yearsRather than populating the drop down with the Id/string of each
TimeZone
object in the collection, why not add the actual objects instead asItem
s 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 over 3 years@ingredient_15939 you are specifying E Australian Standard Time which is ALWAYS +10. E Australian Daylight Saving Time is +11.