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

旧街凉风 提交于 2019-12-10 23:57:02

问题


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:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/1637144/user-datetime-setting-as-gmt-how-to-convert-date-to-their-localized-setting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!