views:

174

answers:

3

In my users setting I have a dropdown with all the GMT dates for the user to select.

In c#, how would I convert a datetime stored in the database to their GMT time?

The time stored in the database is the servers time.

+1  A: 

I take it you're storing the GMT difference for each user? I.e. 0 or +1 or -6, etc?

// Get your DateTime to convert
DateTime databaseDateTime = DateTime.Now;
double userGmtOffset = 1;

// Get the GMT time of the database time
int hoursOffset = TimeZone.CurrentTimeZone.GetUtcOffset(databaseDateTime).Hours;
DateTime gmtDateTime = databaseDateTime.AddHours((double)(0 - hoursOffset));
DateTime userDateTime = gmtDateTime.AddHours(userGmtOffset);
GenericTypeTea
yes datetime is servers time interally.
mrblah
I've made some changes so this should do the trick now... Although I'm not sure regarding what happens with daylight savings. So I look forward to feedback.
GenericTypeTea
A: 

Use System.DateTimeOffset instead of DateTime. IT includes all the functionality you need.

adrianm
+2  A: 

For .NET 3.5+, you can store the system time zone identifier with the user (you can get those from TimeZoneInfo.GetSystemTimeZones) and use TimeZoneInfo to convert between time zones:

// In a User class that has a string timeZoneId field (for example)
public DateTime GetLocalDateTime(DateTime originalDate) {
    DateTime utcDate      = TimeZoneInfo.Local.ConvertToUtc(originalDate);
    TimeZone userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(this.timeZoneId);
    return   TimeZone.ConvertTime(utcDate, userTimeZone);
}

In .NET 2.0, you're limited to the older TimeZone class which is only available for the local system. You don't automatically get daylight savings information for the user, so you'd have to store that yourself alongside the basic GMT/UTC offset.

// In a User class that has a double utcOffset field (for example)
public DateTime GetLocalDateTime(DateTime originalDate) {
    DateTime utcDate = TimeZone.CurrentTimeZone.ToUniversalTime(originalDate);
    return utcDate.AddHours(this.utcOffset);
}

// Usage
DateTime localDate = user.GetLocalDateTime(DateTime.Now);
Jeff Sternal