DelphiFAQ Home Search:
General :: Programming :: Delphi
General Delphi related information.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.
Recommended links on this topic:
Featured Article

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; 
 
 
You don't like the formatting? Check out SourceCoder then!
Generated 12:01:50 on Jul 20, 2017