Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Get timezone offset by timezone name

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!

like image 744
Daniil Harik Avatar asked Jun 05 '10 07:06

Daniil Harik


People also ask

How do I find the offset of time zones?

You can get the offset of a timezone using ZonedDateTime#getOffset . Note that the offset of a timezone that observes DST changes as per the changes in DST. For other places (e.g. India), it remains fixed. Therefore, it is recommended to mention the moment when the offset of a timezone is shown.

How do you read UTC offset?

A UTC offset is the difference in hours and minutes between a particular time zone and UTC, the time at zero degrees longitude. For example, New York is UTC-05:00, which means it is five hours behind London, which is UTC±00:00.

How do I fetch the timezone of a user?

getTimezoneOffset()/60; The method getTimezoneOffset() will subtract your time from GMT and return the number of minutes. So if you live in GMT-8, it will return 480. To put this into hours, divide by 60.


3 Answers

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); 
like image 190
Oded Avatar answered Sep 29 '22 11:09

Oded


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?

like image 32
Dean Harding Avatar answered Sep 29 '22 12:09

Dean Harding


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);
like image 45
kingdango Avatar answered Sep 29 '22 11:09

kingdango