如何在Delphi中格式化Unix时间戳?

时间:2010-12-12 02:49:15

标签: delphi

我有

var timestamp: Longint;  
timestamp := Round((Now() - 25569.0 {Unix start date in Delphi terms} ) * 86400);

我在一些MySql中使用它作为主键。

但我也希望格式化日期/时间,例如PHP's date() function

有没有人有代码段或网址?

3 个答案:

答案 0 :(得分:31)

您正在寻找

function DateTimeToUnix(const AValue: TDateTime): Int64;

function UnixToDateTime(const AValue: Int64): TDateTime;
来自DateUtils.pas的

函数

TDateTime值可以通过 FormatDateTime 功能

进行格式化

答案 1 :(得分:15)

这要快得多

// 4x faster than dateutils version
function UNIXTimeToDateTimeFAST(UnixTime: LongWord): TDateTime;
begin
Result := (UnixTime / 86400) + 25569;
end;

// 10x faster than dateutils version
function DateTimeToUNIXTimeFAST(DelphiTime : TDateTime): LongWord;
begin
Result := Round((DelphiTime - 25569) * 86400);
end;

答案 2 :(得分:3)

按照@kludg的建议,我会使用DateTimeToUnix

function DateTimeToUnix(const AValue: TDateTime): Int64;

如果要使用毫秒格式的当前Unix时间戳,可以实现以下功能:

function UNIXTimeInMilliseconds: Int64;
var
  DateTime: TDateTime;
  SystemTime: TSystemTime;
begin
  GetSystemTime(SystemTime);
  DateTime := SysUtils.EncodeDate(SystemTime.wYear, SystemTime.wMonth, SystemTime.wDay) +
        SysUtils.EncodeTime(SystemTime.wHour, SystemTime.wMinute, SystemTime.wSecond, SystemTime.wMilliseconds);
  Result := DateUtils.MilliSecondsBetween(DateTime, UnixDateDelta);
end;