I have
var timestamp: Longint;
timestamp := Round((Now() - 25569.0 {Unix start date in D开发者_高级运维elphi 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?
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
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;
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;
精彩评论