求Delphi中日期时间相减的方法
如题。
s1, s2: string; //日期时间是字符串型
s1 := '2013-06-28 15:44:50';
s2 := '2013-06-28 16:47:51';
//我如何得到格式为 '00天01小时03分01秒' 的结果?
[解决办法]
DateUtils单元中的SecondsBetween
返回的是int64,表示的是秒数,然后你自己算就好了
[解决办法]
先将字符串转换成日期格式,然后用下面的代码处理:http://bbs.csdn.net/topics/390395202
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DateUtils, ComCtrls, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
DateTimePicker1: TDateTimePicker;
DateTimePicker2: TDateTimePicker;
DateTimePicker3: TDateTimePicker;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
function TimeBetween(A, B: TDateTime): string;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Lines.Add(TimeBetween(DateTimePicker1.Date, DateTimePicker2.Date));
end;
function TForm1.TimeBetween(A, B: TDateTime): string;
var
Y, M, Day: Integer;
C, D: TDateTime;
sA, sB: string;
begin
if Trunc(A) > Trunc(B) then
begin
Result := 'Error';
exit;
end;
if Trunc(A) = Trunc(B) then
begin
Result := '0Y0M0D';
exit;
end;
Y := YearsBetween(B, A);
M := MonthsBetween(B, A);
M := M - Y * MonthsPerYear;
Day := DaysBetween(B, A) - Trunc(Y * ApproxDaysPerYear) - Trunc(M * ApproxDaysPerMonth);
Result := IntToStr(Y) +'Y'+ IntToStr(M) +'M'+ IntToStr(Day) +'D';
end;
end.
[解决办法]
const
s1 = '2013-06-28 15:44:50';
s2 = '2013-06-28 16:47:51';
var t,tmp:TDatetime;
d,h,n,s:integer;
str:string;
begin
t:=abs(strtodatetime(s2)-strtodatetime(s1));
d:=round(t);
h:=round((t-d)*24);
tmp:=d+h/24;
n:=round((t-tmp)*1440);
tmp:=tmp+n/1440;
s:=round((t-tmp)*86400);
str:=inttostr(d)+'天'+inttostr(h)+'小时'+inttostr(n)+'分'+inttostr(s)+'秒';
if s1>s2 then str:='负了'+str;
showmessage('时间:'+#13+' '+s2
+#13+'减去'+#13+' '+s1
+#13+#13+'结果为:'+str);
[解决办法]
转成日期,相减,再按整数对应天,1/24对应1小时,1/1440对应1分钟,1/86400对应1秒钟来组成字符串。
[解决办法]
完美无错运行
uses
SysUtils, DataUtils;
var
S1, S2: string;
T1, T2: TDateTime;
D, H, M, S: Integer;
Value: Int64;
begin
DateSeparator := '-';
S1 := '2013-06-28 15:44:50';
S2 := '2013-06-28 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]);
end;