我需要函数 DateTimeToUnix
和 UnixToDateTime
的 UTC 变体,以便中国客户能够与德国的服务器进行交互。双方应该能够交换 Unix 时间戳(UTC 格式,无 DST)并能够通过这种方式进行通信。
在bugreport of HeidiSQL中,用户讨论 DateTimeToUnix
和 UnixToDateTime
不关心时区,我发现了以下代码:
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。
最佳答案
您已经找到了 DateTimeToUnix
和 UnixToDateTime
。因此,这部分转换已得到处理。
您现在需要做的就是在本地时间和 UTC 时间之间进行转换。您可以使用 DateUtils.TTimeZone
来做到这一点类(class)。特别是 DateUtils.TTimeZone.ToUniversalTime
和 DateUtils.TTimeZone.ToLocalTime
。
这四个功能可以满足您的所有需求。
关于delphi - UTC 格式的 DateTimeToUnix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23968919/