在我的用户设置中,我有一个下拉菜单,其中包含所有 GMT 日期供用户选择。
在 C# 中,如何将数据库中存储的日期时间转换为 GMT 时间?
数据库中存储的时间为服务器时间。
对于 .NET 3.5+,您可以将系统时区标识符与用户一起存储(您可以从TimeZoneInfo.GetSystemTimeZones
)并使用TimeZoneInfo
在时区之间转换:
// 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);
}
在 .NET 2.0 中,您只能使用较旧的版本TimeZone
类仅适用于本地系统。您不会自动获取用户的夏令时信息,因此您必须自己将其与基本 GMT/UTC 偏移量一起存储。
// 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)