Convert DateTime from UTC to a user provided time

2019-07-28 09: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?

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-28 09:38

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 .

查看更多
看我几分像从前
3楼-- · 2019-07-28 09:52

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.

查看更多
登录 后发表回答