How to get the difference between two dates in days and hours?

hidrau
hidrau used Ask the Experts™
on
Hello Guys

I have two variable in this format:  dd/mm/yyyy hh:mm:ss

StartDate = '01/11/2017 13:00:00'  
EndDate  = '02/11/2017  13:30:00'

How to get the difference between these two dates in days and hours

ddd  hh:mm:ss
001   01:30:00

Thanks
Alex
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
NorieAnalyst Assistant
Commented:
Alex

I'm sure there are better ways, bit rusty with Delphi/Pascal, but this worked for me.
uses
  System.SysUtils, DateUtils, Math;


var StartDate, EndDate, ElapsedTime :TDateTime;
    Dy, Hr,Mn,Sc, Msc:Word;
begin

  StartDate:=encodedatetime(2017,11,1,13,00,00,00);
  EndDate:=encodedatetime(2017,11,2,13,30,00,00);

  Dy:=daysbetween(StartDate, EndDate);

  ElapsedTime:= EndDate-StartDate;

  DecodeTime(ElapsedTime,Hr,Mn,Sc,Msc);

  writeln(Output, inttostr(Dy)+' days '+inttostr(Hr)+' hours ' + inttostr(Mn) +' mins');

  readln;

end.

Open in new window

Software architect
Top Expert 2012
Commented:
Which Delphi version you use?
In older (<XE) I would go with:
function GetMyDate(sDate: String): TDateTime;
var
  tmpDTFormat,tmpTMFormat: String;
  tmpDTSeparator: Char;
begin
  tmpDTFormat:=ShortDateFormat;
  tmpTMFormat:=ShortTimeFormat;
  tmpDTSeparator:=DateSeparator;
  try
    ShortDateFormat:='dd/mm/yyyy';
    ShortTimeFormat:='hh:nn:ss';
    DateSeparator:='/';
    Result:=StrToDateTime(sDate);
 finally
    ShortDateFormat:=tmpDTFormat;
    ShortTimeFormat:=tmpTMFormat;
    DateSeparator:=tmpDTSeparator;
  end;
end;

...
dtStart:=GetMyDate('01/11/2017 13:00:00');
dtEnd:=GetMyDate('02/11/2017 13:30:00');

ddd := DaysBetween(dtEnd, dtStart);
dtEnd := IncDay(dtEnd, -ddd);

hh := HoursBetween(dtEnd, dtStart);
dtEnd := IncHour(dtEnd, -hh);

nn := MinutesBetween(dtEnd, dtStart);
dtEnd := IncMinute(dtEnd, -nn);

ss := SecondsBetween(dtEnd, dtStart);
...

Open in new window

Geert GOracle dba
Top Expert 2009
Commented:
a date is stored as a float in Delphi
(not the text representation)
the fractional part is the time, the whole part is the day

with a little math:
dt := encodedatetime(2017,11,2,13,30,00,00) - encodedatetime(2017,11,1,13,00,00,00);

days := trunc(dt);
hours := trunc((dt - trunc(dt)) * 24);
minutes := trunc((dt - trunc(dt) - hours/24) * 60);
seconds := trunc((dt-trunc(dt) - hours/24 - minutes/24/60) * 60;

Open in new window

Author

Commented:
thanks a lot for the help

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial