How to format a Unix timestamp in Delphi?

You are looking for

function DateTimeToUnix(const AValue: TDateTime): Int64;

and

function UnixToDateTime(const AValue: Int64): TDateTime;

functions from DateUtils.pas

TDateTime value can be formatted by FormatDateTime function


I would use DateTimeToUnix, as suggested by @kludg.

function DateTimeToUnix(const AValue: TDateTime): Int64;

In case you want the current Unix timestamp in milliseconds format, you can implement the following function:

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;

This is much faster

// 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;

Tags:

Delphi