在Delphi中减去两个TDATETIME变量并以分钟为单位返回结果

Tin*_*ian 2 delphi tdatetime

我有两个TDateTime变量,如下所示:

s := StrToDateTime('03/03/2017 10:10:12');
e := StrToDateTime('04/04/2017 10:10:12');
Run Code Online (Sandbox Code Playgroud)

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

这些...Between()功能在这里没有帮助我。

LU *_* RD 6

使用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.
Run Code Online (Sandbox Code Playgroud)

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


如果要以分钟为单位,请使用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;
Run Code Online (Sandbox Code Playgroud)


Ken*_*ite 5

您可以使用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.
Run Code Online (Sandbox Code Playgroud)

  • @Remy:已更新。(当我让她担任演讲者时,母亲讨厌它。) (2认同)