DelphiFAQ Home Search:

How to convert a Unix timestamp to the TDateTime format

 

comments8 comments. Current rating: 5 stars (4 votes). Leave comments and/ or rate it.

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!
Content-type: text/html

Comments:

2008-06-08, 06:23:16   (updated: 2008-06-08, 06:36:33)
anonymous from Australia  
rating
works well.
2009-05-25, 22:26:33
anonymous from Indonesia  
Very good... thank you!
2009-07-22, 04:42:26
anonymous from United States  
Many thanks from explanations!
2010-01-05, 14:28:12
joe from United States  
rating
Worked Great !!!!

Thanks!
2011-10-03, 12:46:44
from Brazil  
rating
Funciona muito bem!! Obrigado!!
2012-03-27, 11:19:04
anonymous from United Kingdom  
Works Well, as long as you remember to take off the last 3 digits on JMeter time stamps !
2014-04-11, 15:48:14
anonymous from Iran  
Very Thanks :)
2017-06-14, 16:43:19
Sebastian from Galati, Romania  
rating
I must say you have high quality content here. Your page should
go viral. You need initial boost only. How to get it?

Search for; Miftolo's tools go viral

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: