delphi计算两个时间差  
官方Delphi 学习QQ群: 682628230(三千人)
频道

delphi计算两个时间差


uses DateUtils;
 
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,代码如下:


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;

推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.043717861175537 seconds