简体   繁体   中英

.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!

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?

您应该利用TimeZoneInfoConvertTime方法来处理您基于您指定的TimeZone的日期,而不是进行一些手动添加。

var localizedDateTime = TimeZoneInfo.ConvertTime(yourDateTime, localTimeZoneInfo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM