var
S1, S2: string;
T1, T2: TDateTime;
D, H, M, S: Integer;
Value: Int64;
begin
S1 := '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;
经过上面可以实现两个时间相减的功能,然后将其写成函数为:
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;
调用: var Caption: string; begin Caption := GetSubDateTime(S1, S2); memo1.liens.add(Caption); end;
上面就可以直接调用函数计算差值,若要想计算动态的时间差值就使用一个计时器Timer,代码如下: