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!
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.
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.
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.
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);
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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With