Subtract two TDATETIME variables in Delphi and return the result in minutes

Tina Soltanian picture Tina Soltanian · Apr 5, 2017 · Viewed 9k times · Source

I have two TDateTime variables, like this:

s := StrToDateTime('03/03/2017 10:10:12');
e := StrToDateTime('04/04/2017 10:10:12');

I need to find out the difference between them, in hh:mm:ss format.

The ...Between() functions are not helping me here.

Answer

LU RD picture LU RD · Apr 5, 2017

Use the DateUtils.SecondsBetween function:

Uses
  DateUtils,SysUtils;

function TimeDiffStr(const s1,s2: String): String;
var
  t1,t2: TDateTime;
  secs: Int64;
begin
  t1 := StrToDateTime(s1); 
  t2 := StrToDateTime(s2); 
  secs := SecondsBetween(t1,t2);
  Result := Format('%2.2d:%2.2d:%2.2d',[secs div SecsPerHour,(secs div SecsPerMin) mod SecPerMin,secs mod SecsPerMin]);
end;

begin
  WriteLn(TimeDiffStr('03/03/2017 10:10:12','04/04/2017 10:10:12'));
  ReadLn;
end.

From the number of seconds, calculate the hours,minutes and remaining seconds.


If you want the difference in minutes, use the DateUtils.MinutesBetween function:

function TimeDiffStr(const s1,s2: String): String;
var
  t1,t2: TDateTime;
  minutes: Int64;
begin
  t1 := StrToDateTime(s1); 
  t2 := StrToDateTime(s2); 
  minutes := MinutesBetween(t1,t2);
  Result := Format('%2.2d:%2.2d:%2.2d',[minutes div MinsPerHour,minutes mod MinsPerHour,0]);
end;