减去 Delphi 中的两个 TDATETIME 变量和 return 中的结果(以分钟为单位)

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

我有两个 TDateTime 变量,像这样:

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

我需要以 hh:mm:ss 格式找出它们之间的区别。

...Between() 函数在这里对我没有帮助。

使用DateUtils.SecondsBetween函数:

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.

根据秒数,计算小时、分钟和剩余秒数。


如果您想要以分钟为单位的差异,请使用 DateUtils.MinutesBetween 函数:

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;

您可以使用 TTimeSpan(来自 System.TimeSpan 单元)。

program Project1;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, System.TimeSpan;

var
  StartDate, EndDate: TDateTime;
  TS: TTimeSpan;
  Temp: string;
begin
  StartDate := StrToDateTime('03/03/2017 10:10:12');
  EndDate := StrToDateTime('04/04/2017 10:10:12');
  TS := TTimeSpan.Subtract(EndDate, StartDate);
  Temp := TS;
  WriteLn(Temp);  // Outputs 32.00:00:00
  // The next line outputs the same as the one above
  WriteLn(Format('%.2d:%.2d:%.2d:%.2d', [TS.Days, TS.Hours, TS.Minutes, TS.Seconds]));
  WriteLn(TS.TotalMinutes); // Outputs 4.60800000000000E+0004
  WriteLn(Trunc(TS.TotalMinutes)); // Outputs 46080

  // This one will give the output you want (768:00:00)
  WriteLn(Format('%.2d:%.2d:%.2d', [TS.Days * 24 + TS.Hours, TS.Minutes, TS.Seconds]));
  ReadLn;
end.

首先,不要对 date/time 值使用硬编码字符串。这会受到本地化问题的影响,而且无论如何都会浪费开销。使用 SysUtils.EncodeDate()SysUtils.EncodeTime() 函数,或 DateUtils.EncodeDateTime() 函数。

其次,...Between()的功能确实可以使用,特别是SecondsBetween()。您可以根据该 return 值计算各个组件。

尝试这样的事情:

uses
  ..., SysUtils, DateUtils;

var
  s, e: TDateTime;
  diff: Int64;
  days, hours, mins, secs: Integer;
  s: string;
begin
  s := EncodeDateTime(2017, 3, 3, 10, 10, 12, 0);
  e := EncodeDateTime(2017, 4, 4, 10, 10, 12, 0);

  diff := SecondsBetween(e, s);

  days := diff div SecsPerDay;
  diff := diff mod SecsPerDay;

  hours := diff div SecsPerHour;
  diff := diff mod SecsPerHour;

  mins := diff div SecsPerMin;
  diff := diff mod SecsPerMin;

  secs := diff;

  s := Format('%d:%d:%d:%d', [days, hours, mins, secs]);
end;