我使用一个遗留的DMS应用程序,它使用GMT 0(格林威治)作为默认时区存储日期,并对其应用1小时时差。我必须用GridView显示这些记录,我需要根据我的系统运行的相对位置(例如伦敦,巴哈马)应用一种转换。
查看遗留系统如何处理日期,我设计了以下算法来正确显示日期(我的代码基于asp.net/c#):
//Example for Bahamas, GMT: -5 Hours as offset, I should add 4 hours to the DB date
//Example for London, GMT: 0 Hour as offset, I should add 1 hour to the DB date
DateTime dateToDisplay;
int spreadHours = 0;
TimeZone cur = TimeZone.CurrentTimeZone;
DaylightTime daylight = cur.GetDaylightChanges(dateFromDb.Year);
DateTime start = daylight.Start;
DateTime end = daylight.End;
if (dateFromDb.CompareTo(start) <= 0 || dateFromDb.CompareTo(end) >= 0)
{
spreadHours = -1 - (cur.GetUtcOffset(dateFromDb).Hours);
}
else
{
spreadHours = - (cur.GetUtcOffset(dateFromDb).Hours);
}
dateToDisplay = dateFromDb.AddHours(spreadHours);
但是,我不确定这个过程是否可以涵盖所有情况,或者是否可以有更好的解决方案来达到相同的结果。
谁能证实我的想法或建议一个更好的路径?
一般来说,从。net 3.5开始,你可以/应该使用TimeZoneInfo类,
实际上,要将UtcDateTime转换为本地时间,您需要做的就是:
// here static text but you can initialize the TimeZoneInfo with any Id, check MSDN for this:
// http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);
你可以在SO中查看其他问题和答案:
将UTC/GMT时间转换为本地时间
处理时区并不像您想象的那么明确。
阅读以下Troy Hunt的文章:
http://www.troyhunt.com/2011/08/overcoming-sql-08s-globally-insensitive.html他非常详细地介绍了。net中的时区处理,这是一篇很好的文章,可以快速告诉您陷阱(和可能的解决方案)是什么。
快速查看MSDN建议您可以这样做
DateTime dt = new DateTime(dateFromDb.Ticks, DateTimeKind.Utc);
DateTime dtLocal = dt.ToLocalTime();
然后你可以用任何你想要的格式显示dtLocal。它将被调整为具有正确夏令时设置的当地时间
查看MSDN DateTime。ToLocalTime获取更多信息
Edit:我假设这里dateFromDb是DateTime Class的一个实例。