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

9gm1akwq  于 2023-08-04  发布在  其他
关注(0)|答案(3)|浏览(128)

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

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

字符串
我需要找出它们之间的区别,以hh:mm:ss
...Between()函数对我没有帮助。

zfycwa2u

zfycwa2u1#

使用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;

b1zrtrql

b1zrtrql2#

您可以使用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.

字符串

rggaifut

rggaifut3#

首先,不要对日期/时间值使用硬编码字符串。这会受到本地化问题的影响,而且无论如何都只是浪费开销。使用SysUtils.EncodeDate()SysUtils.EncodeTime()函数,或DateUtils.EncodeDateTime()函数。
第二,...Between()函数确实可以使用,特别是SecondsBetween()。您可以根据该返回值计算各个组件。
试试这样的方法:

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;

字符串

相关问题