ahmd0
ahmd0

Reputation: 17313

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

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?

Upvotes: 1

Views: 5256

Answers (2)

Alok
Alok

Reputation: 352

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 .

Upvotes: 3

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

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.

Upvotes: 7

Related Questions