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.
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.
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);
Use System.DateTimeOffset instead of DateTime. IT includes all the functionality you need.
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);