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

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

 2019-12-18 
delphitdatetime

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

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

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

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

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

相关讨论

使用DateUtils.SecondsBetween函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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函数:

1
2
3
4
5
6
7
8
9
10
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单元)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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.

相关讨论

首先,请不要对日期/时间值使用硬编码的字符串。 这会受到本地化问题的影响,无论如何它只是在开销上的浪费。 使用SysUtils.EncodeDate()和SysUtils.EncodeTime()函数,或DateUtils.EncodeDateTime()函数。

其次,确实可以使用...Between()函数,尤其是SecondsBetween()。 您可以根据该返回值计算各个组成部分。

尝试这样的事情:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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;

(0)

相关推荐