2

How can I get universal time for a specified TimeZone, given a DateTime object? My application (a Timer) asks the user to specify a time and a timezone and I need to save the UTC based on the specified time+timezone values.

For example, user A specifies
DateTime: 07/06/2011 7:30 AM TimeZone: Eastern Standard Time (-5:00).

User B specifies:
DateTime: 07/06/2011 05:00 PM TimeZone: India Standard Time (+5:30).

I believe the UTC for both the above DateTime values will be the same and both of the above timers will occur at the same time. The problem is how do I get the UTC to save in the database? I am not able to get matching UTCs for the above datetime values.

A9S6
  • 6,575
  • 10
  • 50
  • 82

2 Answers2

4

You can use DateTime in combination with TimeZoneInfo:

var utc = TimeZoneInfo.ConvertTimeToUtc(dateTimeAsEnteredByUser,
                                        timeZoneChosenByUser);

You need to make sure, that the Kind property of dateTimeAsEnteredByUser is set to DateTimeKind.Unspecified.

BTW:
The two times you specified are not the same. The first is 12:30 UTC and the second one is 11:30 UTC. Additionally, 17:00 PM doesn't exist, it's either 17:00 or 5:00 PM.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • +1: I have changed the time to 05:30 PM. Strange these two times are not same, could this be because of the daylight savings? (-5:00) + (5:30) should be 10:30 hours difference.no? – A9S6 Jul 06 '11 at 12:04
  • Marked this one as an answer for the extra "DateTimeKind" info. :) – A9S6 Jul 06 '11 at 12:05
  • @A9S6: Yes, -5:00 + 5:30 is a difference of 10:30. But the times you provided are only 9:30 apart... Just do the calculation: 17 - 7.5 = 9.5 and not 10.5 – Daniel Hilgarth Jul 06 '11 at 12:07
  • Yes, but my Windows 7 clocks (additional clock set to -5:00 timezone) shows 5:00 PM as my time and 7:30 AM as time in (-5:00) timezone. – A9S6 Jul 06 '11 at 12:39
  • 1
    In this context, it might be the effect of daylight savings time, right. Which timezone is your addition clock set to exactly? Currently, DST is active in the USA for example, so it really is UTC-4:00 and not UTC-5:00. So, I need to revoke my comment from above: Your times are the same, because the user selected "Eastern Standard Time" and not "UTC-5:00". Sorry for the confusion. – Daniel Hilgarth Jul 06 '11 at 12:46
1

Converting to Utc:

DateTime utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone);
Peter
  • 27,590
  • 8
  • 64
  • 84