Calculating the difference between 2 times regardless of the days passed
Hi
i am very new to delphi and have only been working with it for a few months, i need to calculate the difference between 2 TDateTime Variables regardless of the number of days passed.
now i understand that this code will only work up until 24:00:00, i need to make this piece of code so that it calculates the time difference over 24 hours in hh:mm:ss format.
The TDateTime is a Double Type.
The fractional part handles the time only.
VAR
td,t :TDateTime;
BEGIN
td=Now; // Both Time and Date in one double.
t:=FRAC(td); // Variable t now holds Only the Time portion.
IF t<0 THEN t:=t*-1 // If t is negative then make it positive.
// The time is never a negative number, but the date can be.
END.
This tiny example should give you the input needed.
your existing code work fine, but you must take away the date information and make sure negative numbers is made positive.
thanks for your replys but i still cant achieve the result i want.
i will try and explain it a different way.
when the app closes the time is logged and read when it is opened again. I want to compare the current system time with that value and display how long the app has been closed for in hh:mm:ss format.
if i change my code to this instead so im using just Time Values instead of DateTime does that make it any easier?
var
StartTime, EndTime, TimeBetween: TDateTime;
begin
StartTime := (Time); // Current System Time
EndTime := StrToTime(EndTime1.Caption); // Time Software was closed
TimeBetween := ??
Label1.Caption := TimeToStr(TimeBetween);
end;
if i use just Time Values how can i get the difference in hh:mm:ss format between the 2.
i cant just simply subtract the values like in my first example because it needs to be able to count more than just 24 hours.
Hmmmm.. First of all.
Delphi and its Time routines does not handle more than 24 hours with TimeToStr.
At least I do not think so. I must admit that I have not tested this :-)
Anyway. The fractional part, FRAC(DateTime) holds the time only.
The Integer part, holds the date only.
I think you should try to write your own TimeToStr function.
Something like
FUNCTION FullTimeToStr(StartDT,EndDT:TDateTime):STRING;
VAR
sTemp : STRING;
Days,Hours,iTemp : INTEGER;
TimeStart,TimeEnd: TTime;
BEGIN
TimeStart:= StartDT;
TimeEnd := EndDT;
IF TimeStart<0 THEN TimeStart:=TimeStart*-1; // Makes negative number positive.
IF TimeEnd<0 THEN TimeEnd:=TimeEnd*-1; // Makes negative number positive.
sTemp := TimeToStr(TimeStart-TimeEnd);
iTemp := StrToInt(Copy(sTemp,1,2));
Days := INT(EndDT)-INT(StartDT);
IF Days <0 Then Days := Days *-1; // Makes negative number positive.
Hours:=Days*24+iTemp;
Result:=IntToStr(Hours)+COPY(sTemp,3,5);
END;
I am a little bit unsure of the way I use INT on a value that is a double. Might get an error on that one, but the code should at least give you some ideas.
Good luck.