20

I have

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

which I am using as a primary key in some MySql stuff.

But I would also like to format the date/time, like PHP's date() function does.

Does anyone have a code snippet or URL?

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551

4 Answers4

47

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

kludg
  • 27,213
  • 5
  • 67
  • 118
23

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;
hikari
  • 3,393
  • 1
  • 33
  • 72
  • +1 thanks. I don't do it too often, but this is useful to know – Mawg says reinstate Monica Feb 23 '11 at 07:25
  • 1
    Note that DateTimeToUNIXTimeFAST has a slight difference from the DateUtils version, if milliseconds = 500..999, DateUtils will round backwards, while FAST version will round up towards the next second. – hikari Jan 05 '14 at 20:37
  • 1
    Result := Trunc((DelphiTime - 25569) * 86400); – wittrup Mar 06 '14 at 18:13
  • 8
    Including `SysUtils` unit you could write the same as `(UnixTime / SecsPerDay) + UnixDateDelta` and `Round((DelphiTime - UnixDateDelta) * SecsPerDay)`. – TLama Mar 11 '14 at 16:51
7

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;
Mauricio
  • 71
  • 1
  • 4
1

The above mentioned function UNIXTimeToDateTimeFAST should use Int64 and not Longword. For older dates (negative values) Longword gives wrong results.

David
  • 11
  • 2