1

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?

ahmd0
  • 16,633
  • 33
  • 137
  • 233

2 Answers2

6

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.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • Thanks alot! One follow-up question. If I want to store a list of time zones for a user to select, what property of TimeZoneInfo is better to store in a DropDownCtrl value? – ahmd0 Jul 24 '12 at 03:14
  • Seems like the time zone's Id would be a reasonable property – Andrew Whitaker Jul 24 '12 at 03:16
  • My only concern about it is that ID is a string, something like "Pacific Standard Time (Mexico)" and not just a number. I'm somewhat concerned about localization? – ahmd0 Jul 24 '12 at 03:19
  • 1
    Ah okay. In that case, `BaseUtcOffset.TotalHours` might work. – Andrew Whitaker Jul 24 '12 at 03:22
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 .

Alok
  • 342
  • 2
  • 8
  • Nice addition. Thanks. Just curious, is there any way to get a time zone selected in a user's web browser? – ahmd0 Jul 24 '12 at 03:34
  • GetCurrent Time Zone using TimeZone.CurrentTimeZone and find it using it's standard name in list lstTZI . – Alok Jul 24 '12 at 07:13