用户日期时间设置为GMT,如何将日期转换为本地化设置? [英] user datetime setting as GMT, how to convert date to their localized setting?
问题描述
在c#中,我如何转换存储在数据库中的日期时间到他们的GMT时间?
数据库中存储的时间是服务器的时间。
对于.NET 3.5+,您可以与用户一起存储系统时区标识符(您可以从 TimeZoneInfo.GetSystemTimeZones
获取它们),并使用 TimeZoneInfo
在时区之间进行转换:
//在具有一个字符串timeZoneId字段(例如)
public DateTime GetLocalDateTime(DateTime originalDate){
DateTime utcDate = TimeZoneInfo.Local.ConvertToUtc(originalDate);
TimeZone userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(this.timeZoneId);
返回TimeZone.ConvertTime(utcDate,userTimeZone);
}
在.NET 2.0中,您仅限于较旧的 TimeZone
类,仅适用于本地系统。您不会自动获得用户的夏令时信息,因此您必须将其自己存储在基本的GMT / UTC偏移量旁边。
//在具有双utcOffset字段的用户类中(例如)
public DateTime GetLocalDateTime(DateTime originalDate){
DateTime utcDate = TimeZone.CurrentTimeZone.ToUniversalTime(originalDate);
return utcDate.AddHours(this.utcOffset);
}
//用法
DateTime localDate = user.GetLocalDateTime(DateTime.Now);
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.
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);
这篇关于用户日期时间设置为GMT,如何将日期转换为本地化设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!