.NET Get timezone offset by timezone name

2020-05-30 03:06发布

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!

3条回答
Anthone
2楼-- · 2020-05-30 03:27

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);
查看更多
啃猪蹄的小仙女
3楼-- · 2020-05-30 03:39

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?

查看更多
Bombasti
4楼-- · 2020-05-30 03:51

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);
查看更多
登录 后发表回答