• Status: Solved
• Priority: Medium
• Security: Public
• Views: 210

# DateTime Code

Has anyone got any code that gives me the difference between two datetimes.  i.e I want to use 01/01/1990 10:00:00 compared with 02/01/1990 11:42:56 and get the result 1 day, 1 hour, 42 mins and 56 secs.
Thanks

John.
0
WoodyJ3
• 3
• 2
• 2
• +1
1 Solution

Commented:
Subtract one from the other, and multiply by 86400.  This is the difference between two TDateTimes in seconds.
0

Commented:
WoodyJ3,

reject the given answer. The correct way of doing what you want is:

Var
D1, D2, DifD : TDateTime;
Days, HH, MM, SS   : word;
begin

{ D1 and D2 receive the values from a function or something }

DifD := D2 - D1; // considering  D2 > D1
Days := trunc(DifD);
DecodeTime(DifD, HH, MM, SS);
{ At this point Days has the number of vays between the 2 dates and HH, MM and SS have the values for hours, minutes and seconds }

end;

yours,

Alex
0

Commented:
following..
0

Author Commented:
Sorry, simonet had what I wanted.
0

Author Commented:
simonet, post an answer for the points.

Thanks

John.
0

Commented:
Reject or not, my answer is correct and complete.  A TDateTime is stored with the date in the whole part (in days from 30/12/1899), and the part of the day in the fractional part (for instance, .5 = 1/2 day, i.e. 12 hours).  This means that a single TDateTime is in days, and subtracting one from another gives days.  The difference of two = the difference in days, multiplying by 86400, gives the difference in seconds, and it's far quicker than calling DecodeTime.
0

Author Commented:
Sorry but my question was quite clear.  I wanted the answer in seconds, Minutes, Hours, Days, Months and years not just seconds.

John.
0

Commented:
Thank you, John. Here it goes again, now as an answer:

Var
D1, D2, DifD : TDateTime;
Days, HH, MM, SS   : word;
begin
{ D1 and D2 receive the values from a function or something }
DifD := D2 - D1; // considering  D2 > D1
Days := trunc(DifD);
DecodeTime(DifD, HH, MM, SS);
{ At this point Days has the number of vays between the 2 dates and HH, MM and SS have the values for hours, minutes and seconds }

end;

sburck,

If John wanted only seconds, then I agree your answer would be correct. However, in order to transform seconds in D, H, M, S, the math envolved, even ´though it is easy stuff, would make the routine slower than using Trunc and DecodeTime. Besides, by using Trunc and DecodeTime, the function becomes very short and easy to read, which easens the maintenance process.

yours,

Alex
0

## Featured Post

• 3
• 2
• 2
• +1
Tackle projects and never again get stuck behind a technical roadblock.