How to format a Unix timestamp in Delphi?

前端 未结 3 1227
[愿得一人]
[愿得一人] 2021-02-04 07:36

I have

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

which I am using as a prima

相关标签:
3条回答
  • 2021-02-04 07:46

    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;
    
    0 讨论(0)
  • 2021-02-04 07:54

    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;
    
    0 讨论(0)
  • 2021-02-04 08:03

    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

    0 讨论(0)
提交回复
热议问题