我正在使用 Delphi,并且尝试在数据库中使用 UTC 日期时间存储记录,然后当客户端在本地日期时间中读取它时将其恢复?知道如何进行此来回转换吗?
最佳答案
这是我用来从 UTC 转换为本地时间的函数。
function LocalDateTimeFromUTCDateTime(const UTCDateTime: TDateTime): TDateTime;
var
LocalSystemTime: TSystemTime;
UTCSystemTime: TSystemTime;
LocalFileTime: TFileTime;
UTCFileTime: TFileTime;
begin
DateTimeToSystemTime(UTCDateTime, UTCSystemTime);
SystemTimeToFileTime(UTCSystemTime, UTCFileTime);
if FileTimeToLocalFileTime(UTCFileTime, LocalFileTime)
and FileTimeToSystemTime(LocalFileTime, LocalSystemTime) then begin
Result := SystemTimeToDateTime(LocalSystemTime);
end else begin
Result := UTCDateTime; // Default to UTC if any conversion function fails.
end;
end;
如您所见,该函数按如下方式转换 UTC 日期时间:
- 日期时间 -> 系统时间
- 系统时间 -> 文件时间
- 文件时间 -> 本地文件时间(这是从 UTC 到本地的转换)
- 本地文件时间 -> 系统时间
- 系统时间 -> 日期时间
如何扭转这个局面应该是显而易见的。
<小时/>请注意,此转换将夏令时视为现在,而不是转换时。 DateUtils.TTimeZone
XE 中引入的 type 试图做到这一点。代码变为:
LocalDateTime := TTimeZone.Local.ToLocalTime(UniversalDateTime);
在另一个方向使用ToUniversalTime
。
此类似乎(松散地)以 .net TimeZone
为模型。类。
一句警告。不要指望在转换时考虑夏令时的尝试能够 100% 准确。这是根本不可能实现的。至少没有时光机。这只是考虑到 future 的情况。即使过去的时代也很复杂。 Raymond Chen 在这里讨论了这个问题:Why Daylight Savings Time is nonintuitive .
关于delphi - 如何将德尔福本地时间转换为UTC时间?以及如何将其从 UTC 转换回本地时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15567194/