Convert DateTime from UTC to a user provided time zone with C#

倖福魔咒の 提交于 2020-01-16 03:18:04

问题


Say, if I have a database column that holds date/time in UTC time zone, I can read them into DateTime object in my ASP.NET web app written with C#. How do I convert them to a user provided time zone?


回答1:


This assumes that time has a Kind = DateTimeKind.Utc

You could use ConvertTimeFromUtc:

TimeZoneInfo.ConvertTimeFromUtc(time, userTimeZone);

Or TimeZoneInfo.ConvertTime:

TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Utc, userTimeZone);

You will probably want to check out the MSDN article on TimeZoneInfo.ConvertTime for the ins and outs of the method.

It's probably worth reading all about converting between time zones on MSDN as well. It's more complex than you might think.




回答2:


To get Time Zones list in a system you can use TimeZoneInfo.GetSystemTimeZones() .It will give you a list of all available TimeZones for your system.

      List<TimeZoneInfo>  lstTZI = TimeZoneInfo.GetSystemTimeZones().ToList(); 

Because it is ReadOnlyCollection .Now You can bind this source with your DropDownCntrl .



来源:https://stackoverflow.com/questions/11623472/convert-datetime-from-utc-to-a-user-provided-time-zone-with-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!