Mega Code Archive

 
Categories / Delphi / Examples
 

A simple way to calculate elapsed time (in seconds) using TDateTime!

Title: A simple way to calculate elapsed time (in seconds) using TDateTime! Question: I was in the need of a simple function that could calculate the diffrence in minutes between any two given moments and at the same time this diffrence could varey from 1 minute upto several days,.. perhaps even weeks / months.... Answer: NOTE! I strongly recommend Andreas Schmidt's solution (in the article-comment below) --------------------------------------------------------- What the function does in words: It converts the diffrence between two TDateTime vars (the stop- and starttime) to one single TTimeStamp (containing the diffrence in days and seconds). Now the variable TimeStamp contains the number of days and milliseconds elapsed between the two TDateTimes... or does it ? No. Since TDateTime(0) is to be read as the date '12/30/1899 12:00 am' (in delphi5) i have to get rid of those first thousands of days that just happend to drift by under about 1900 years :) So therefor i decrease the TimeStamp.Date with the acutal ammount of days that TDateTime(0) means (by converting TDateTime(0) to a new timestamp). Now the TimeStamp variable contains nothing but the diffrence in days and milliseconds between these two TDateTime's... and i exit the function by calculating the ammount of seconds elapsed. (notice that the TTimeStamp-milliseconds 'property' is useless since TDateTime doesnt have that kind of accurancy...) hopefully you wont have any problems with converting this result to minutes, hours, days or even weeks if you wish to... ----------------------------------------------------------- function DateTimeDiff(Start, Stop : TDateTime) : int64; var TimeStamp : TTimeStamp; begin TimeStamp := DateTimeToTimeStamp(Stop - Start); Dec(TimeStamp.Date, TTimeStamp(DateTimeToTimeStamp(0)).Date); Result := (TimeStamp.Date*24*60*60)+(TimeStamp.Time div 1000); end;