delphi计算两个时间差-转
uses DateUtils;varS1, S2: string;T1, T2: TDateTime;D, H, M, S: Integer;Value: Int64;beginS1 := '2015/09/23 15:44:50';S2 := '2013/09/22 16:47:51';T1 := StrToDateTime(S1);T2 := StrToDateTime(S2);Value := SecondsBetween(T1, T2);D := Value div SecsPerDay; // 取一天有多少秒 H := Value mod SecsPerDay div SecsPerHour; // 取一天有多少秒M := Value mod SecsPerDay mod SecsPerHour div SecsPerMin;S := Value mod SecsPerDay mod SecsPerHour mod SecsPerMin;Caption := Format('%.2d天 %.2d:%.2d:%.2d', [D, H, M, S]); //%.2d没有两位补全,若没有'.'则显示实际位数memo1.Lines.Add(caption);end; |
经过上面可以实现两个时间相减的功能,然后将其写成函数为:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
function GetSubDateTime(S1, S2:string): string;var T1, T2: TDateTime; D, H, M, S: Integer; Value: Int64;begin T1 := StrToDateTime(S1); T2 := StrToDateTime(S2); Value := SecondsBetween(T1, T2); D := Value div SecsPerDay; H := Value mod SecsPerDay div SecsPerHour; M := Value mod SecsPerDay mod SecsPerHour div SecsPerMin; S := Value mod SecsPerDay mod SecsPerHour mod SecsPerMin; result := Format('%.2d天 %.2d:%.2d:%.2d',[D, H, M, S]);end;<br><br>调用:<br>var<br>Caption: string;<br>begin<br> Caption := GetSubDateTime(S1, S2);<br> memo1.liens.add(Caption);<br>end; |
上面就可以直接调用函数计算差值,若要想计算动态的时间差值就使用一个计时器Timer,代码如下:
|
1
2
3
4
5
6
7
8
9
|
procedure TForm2.Timer1Timer(Sender: TObject);var S1, S2: string;begin S1 := FormatDateTime('yyyy/mm/dd hh:mm:ss', now()); // 我用的XE,所以提前出来的系统时间是这种格式 S2 := '2015/9/22 01:02:03'; // 这里时间要和获取到的系统时间一致 GetSubDateTime(S1, S2); Memo1.Lines.Add(GetSubDateTime(S1, S2));end; |

浙公网安备 33010602011771号