Reputation: 905
I am trying to get the difference between two datetimes and display it in string as hh:mm
q.parambyname('vstart').asdatetime:= vstart;
q.parambyname('vend').asdatetime:= vend;
d:= vend-vstart;
mins:= d * 1440;
q.ParamByName('mins').asBCD:= mins;
currently the database stores it in minutes
example (0.39)
I would like to then take it from database and display it in the string format hh:mm
Upvotes: 13
Views: 24671
Reputation: 1158
Because I needed this, but also a function to go beyond 24 hours, here is a function which also does days.
function dateDiffAsString(fromdate, todate: TDateTime;
const daystring: string = ' d ';
const hourstring: string = ':';
const minutestring: string = ':';
const secondstring : string = '';
const showZeroDays : boolean = true;
const skipZeroPart : boolean = false): string;
var
daysdiff : integer;
outstring : string;
tempdate : tdatetime;
m : int64;
yourHMStr : string;
formatstring: string;
begin
// get the order right
if fromdate > todate then
begin
tempdate := fromdate;
fromdate := todate;
todate := tempdate;
end;
outstring := '';
daysdiff := DaysBetween(fromdate, todate);
outstring := format('%d' + daystring, [daysdiff]);
if (daysdiff = 0) and (showZeroDays = false) then
outstring := '';
tempdate := IncDay(todate, -daysdiff); // reduce problem to hourdifference
if skipZeroPart = false then
begin
m := SecondsBetween(tempdate, fromdate);
formatstring := '%2.2d' + hourstring +
'%2.2d' + minutestring +
'%2.2d' + secondstring;
yourHMStr := Format(formatstring,[m div 3600,(m div 60) mod 60,m mod 60]);
end
else
begin
m := MinutesBetween(tempdate, fromdate);
formatstring := '%2.2d' + hourstring +
'%2.2d' + minutestring;
yourHMStr := Format(formatstring,[m div 60, m mod 60]);
end;
outstring := outstring + yourHMStr;
result := outstring;
end;
Example of use:
var
thendate: Tdatetime;
begin
theDifference.caption := dateDiffAsString(
thendate,
now,
' days ', ' hr ', ' min ', ' sec',
true);
// from = 2024.08.01 10:35:00 to = 2024.08.22 09:17:25
// result = 20 days 22 hr 42 min 25 sec
end;
Upvotes: 0
Reputation: 1179
I can propose this simple code using DateUtils
:
DiffTimeStr:= FormatDateTime('hh:nn:ss', TimeEnd - TimeStart);
Upvotes: 5
Reputation: 34889
In DateUtils
there is a function MinutesBetween
which can be used as such:
m := MinutesBetween(vend,vstart);
yourHMStr := Format('%2.2d:%2.2d',[m div 60,m mod 60]);
Upvotes: 19