How to get elapsed time & format it?
I have two unix timestamps as LONG INT. I want to s开发者_如何学Goubtract start from end to get elapsed time and format it to hh:mm:ss
How do I do this? Thanks
you can use the UnixToDateTime
and the FormatDateTime
functions see this sample
uses
DateUtils,
SysUtils;
var
StartUnixTime : Int64;
EndUnixTime : Int64;
StartDateTime : TDateTime;
EndDateTime : TDateTime;
begin
try
StartUnixTime:=1293062827;
EndUnixTime :=1293070000;
//option 1 converting both unix times to TDatetime and then subtract
StartDateTime:=UnixToDateTime(StartUnixTime);
EndDateTime :=UnixToDateTime(EndUnixTime);
Writeln(Format('Elapsed time %s',[FormatDateTime('hh:nn:ss',EndDateTime-StartDateTime)]));
//option 2 subtract directly and then convert to TDatetime
Writeln(Format('Elapsed time %s',[FormatDateTime('hh:nn:ss',UnixToDateTime(EndUnixTime-StartUnixTime))]));
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
Readln;
end.
Additionally if you wanna get the Years, Months and Days , you can use the YearsBetween
, MonthsBetween
and the DaysBetween
functions in this way.
Writeln(Format('Years %d Months %d Days %d',[YearsBetween(EndDateTime,StartDateTime),MonthsBetween(EndDateTime,StartDateTime),DaysBetween(EndDateTime,StartDateTime)]));
UnixTime1 := 123456;
UnixTime2 := 123460;
Diff := UnixTime2 - UnixTime1;
if Diff > 24 * 60 * 60 then
raise Exception.CreateFmt('Time difference (%s seconds) is longer than a day.', [Diff]);
s := Format('%.2d:.%2d:%.2d', [Diff div 60 div 60, (Diff div 60) mod 60, Diff mod 60]);
This answer did not produce the results I was looking for. I opted to use the OvcDate.DateDiff procedure to give the results I was looking for.
procedure TBCSJEmpdm.q1CalcFields(DataSet: TDataSet);
var
das, mos, yrs : Integer;
begin
OvcDate.DateDiff(DateTimeToStDate(DataSet.FieldByName('fromd').AsDateTime),
DateTimeToStDate(DataSet.FieldByName('tod').AsDateTime), das, mos, yrs);
DataSet.FieldByName('das').AsInteger := das;
DataSet.FieldByName('mos').AsInteger := mos;
DataSet.FieldByName('yrs').AsInteger := yrs;
end;
This approach give the elapsed years, months, and days between two dates. OvcDate requires ovc.inc file. Just let me know if you need these.
精彩评论