Mega Code Archive

 
Categories / Delphi / Examples
 

How to convert a unix timestamp to the tdatetime format

Question: There are various situations where you may need to convert a unix timestamp to the TDateTime format and back, e.g. in a mixed environment where you access files on a Unix system or if you use a mySQL database. How can it be done? Answer: The code below uses the unix start date (1/1/1970) as a TDateTime constant and multiplies (divides) with the amount of seconds per day which is 86400. You can call the functions like this: DateTimeToUnix(now); UnixToDateTime(1002187414); const // Sets UnixStartDate to TDateTime of 01/01/1970 UnixStartDate: TDateTime = 25569.0; function DateTimeToUnix(ConvDate: TDateTime): Longint; begin Result := Round((ConvDate - UnixStartDate) * 86400); end; function UnixToDateTime(USec: Longint): TDateTime; begin Result := (Usec / 86400) + UnixStartDate; end;