开发者

user datetime setting as GMT, how to convert date to their localized setting?

In my users setting I have a dropdown with all the GMT dates for the user to select开发者_如何学Go.

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.


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜