delphi - 如何将德尔福本地时间转换为UTC时间?以及如何将其从 UTC 转换回本地时间?

标签 delphi datetime time delphi-xe2 utc

我正在使用 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/

相关文章:

Windows 10 上的 Delphi - 无法再使用 TSocketConnection 调试远程服务器

python - 不能减去偏移天真和偏移感知日期时间

entity-framework - 为什么 EF5 代码在将可为空的日期时间插入数据库时​​首先使用 datetime2?

MYSQL时间戳转换

delphi - 缺少 SOAP 顶级节点

delphi - 更改过程delphi的TColor属性(不起作用)

windows - Windows 资源管理器中文件夹 "Date Modified"的规则

java - 我该如何格式化这个日期?

c++ - 如何将时间转换为整数

delphi - 类似于 System Internal 的/Microsoft 的 FileMon/Process Monitor 的监视文件