UNIX time function?

Post Reply
S@gittarius
Posts: 98
Joined: Sat May 08, 2010 8:12 pm

UNIX time function?

Post by S@gittarius »

Hi Eugene,
Is there an embedded function to generate UNIX time – seconds that have elapsed since midnight, January 1, 1970?
Regards.
Eugene
Posts: 2940
Joined: Tue Nov 17, 2009 8:05 pm

Re: UNIX time function?

Post by Eugene »

Hi,

coarse variant (with LocalTimeOffset)

Code: Select all

function TimeStamp1970ToDateTime(aTimeStamp: Integer): TDateTime;
begin
  Result := (aTimeStamp / (24 * 60 * 60)) + EncodeDate(1970, 1, 1)
end;

function DateTimeToTimeStamp1970(aDateTime: TDateTime): Integer;
begin
  Result := Round((aDateTime - EncodeDate(1970, 1, 1)) * 24 * 60 * 60)
end;

DateTimeToTimeStamp1970(Now)
S@gittarius
Posts: 98
Joined: Sat May 08, 2010 8:12 pm

Re: UNIX time function?

Post by S@gittarius »

Eugene wrote:Hi,

coarse variant (with LocalTimeOffset)

Code: Select all

function TimeStamp1970ToDateTime(aTimeStamp: Integer): TDateTime;
begin
  Result := (aTimeStamp / (24 * 60 * 60)) + EncodeDate(1970, 1, 1)
end;

function DateTimeToTimeStamp1970(aDateTime: TDateTime): Integer;
begin
  Result := Round((aDateTime - EncodeDate(1970, 1, 1)) * 24 * 60 * 60)
end;
DateTimeToTimeStamp1970(Now)
Hi,
Thank you for your assistance.
I was thinking about something similar and before seeing your answer I came up with the following:

Code: Select all

function DateTimeToUnixTimestamp(dtValue: TDateTime): integer;
  const
    iGMTOffset = 2;   // GMT +2
  var
    h, m, s, ms: integer;
  begin
    DecodeTime(dtValue,h,m,s,ms);
    Result := Int(dtValue - EncodeDate(1970, 1, 1)) * 86400 + (h - iGMTOffset) * 3600 + m * 60 + s;
  end;
For time zones with negative GMT offset iGMTOffset should be negative too.
For now I haven’t thought about the reverse function but if I come up with something new I’ll posted it.
Regards
Post Reply