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?
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);
精彩评论