delphi - UTC 格式的 DateTimeToUnix?

标签 delphi date unix time timestamp

我需要函数 DateTimeToUnixUnixToDateTime 的 UTC 变体,以便中国客户能够与德国的服务器进行交互。双方应该能够交换 Unix 时间戳(UTC 格式,无 DST)并能够通过这种方式进行通信。

bugreport of HeidiSQL中,用户讨论 DateTimeToUnixUnixToDateTime 不关心时区,我发现了以下代码:

function DateTimeToUTC(dt: TDateTime): Int64;
var
  tzi: TTimeZoneInformation;
begin
  Result := DateTimeToUnix(dt);
  GetTimeZoneInformation(tzi);
  Result := Result + tzi.Bias * 60;
end;

MSDN explains twi.Bias如下:

All translations between UTC time and local time are based on the following formula:

UTC = local time + bias

The bias is the difference, in minutes, between UTC time and local time.

这听起来合乎逻辑,但由于我不确定上面的代码是否正确,所以我编写了以下程序来检查它:

// A date in summer time (DST)
Memo1.Lines.add('1401494400'); // 31 May 2014 00:00:00 GMT according to http://www.epochconverter.com/
Memo1.Lines.add(inttostr(DateTimeToUnixUTC(StrToDate('31.05.2014'))));

// A date in winter time
Memo1.Lines.add('567302400'); // 24 Dec 1987 00:00:00 GMT according to http://www.epochconverter.com/
Memo1.Lines.add(inttostr(DateTimeToUnixUTC(StrToDate('24.12.1987'))));

德国当前的输出(GMT+1+DST)为:

1401494400
1401490800
567302400
567298800

我期望的输出是:

1401494400
1401494400
567302400
567302400

我做错了什么?

PS:对于这个项目,我绑定(bind)了 Delphi 6。

最佳答案

您已经找到了 DateTimeToUnixUnixToDateTime。因此,这部分转换已得到处理。

您现在需要做的就是在本地时间和 UTC 时间之间进行转换。您可以使用 DateUtils.TTimeZone 来做到这一点类(class)。特别是 DateUtils.TTimeZone.ToUniversalTimeDateUtils.TTimeZone.ToLocalTime

这四个功能可以满足您的所有需求。

关于delphi - UTC 格式的 DateTimeToUnix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23968919/

相关文章:

linux - 逐行比较两个文件并使用 shell 脚本找到最大和最小的数字

Delphi:启动 MCI 时出现 EMCIDeviceError

德尔福 7 : how to split a string into a TStringList

javascript - 如何比较日期和时刻

php - MySQL 获取上个月而不是特定周

java - 查看来自哪些 jars 类

unix - 将命令输出 append 到不带换行符的文件

delphi - 在 Delphi 中使用指针

delphi - 如何检索 XHR 响应?

date - 2个日期和时间之间的分钟差?