unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, dateutils, ComCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
dd1: TDateTimePicker;
dd2: TDateTimePicker;
Memo1: TMemo;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
function daydis(A, B: TDateTime): integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
function TForm1.daydis(A, B: TDateTime): integer;
//计算原理就是求出(相差的月份*30+相差的天数)
var
t1, t2: Tdate; //判断AB中的小日期给T1,大日期给T2
ydis, mdis, ddis: integer; //年份差,月份差,日差
y1, y2, m1, m2, d1, d2: integer;
//y1,m1,d1表示t1的年月日;y2,m2,d2表示t2的年月日;
begin
if A < B then
begin
t1 := A;
t2 := B
end
else
begin
t1 := B;
t2 := A;
end;
y1 := yearof(t1);
y2 := yearof(t2);
m1 := monthof(t1);
m2 := monthof(t2);
d1 := DayOfTheMonth(t1);
d2 := DayOfTheMonth(t2);
ydis := y2 - y1;
mdis := m2 - m1;
if ydis = 0 then //判断是否同年
begin
if d2 >= d1 then
ddis := d2 - d1
else
begin
mdis := mdis - 1;
ddis := d2 - d1 +DaysInMonth(t1);
end;
end
else
begin
mdis:=12*ydis+m2-m1-1;
{求出t1,t2之间相差的正月数,比如2005-05-06和2006-04-06,之间完整的月有10个.
其中不包括t1的那个月和t2的那个月}
if d2>=d1 then //如果t2的日期大于t1的日期,说明还要多一个月,
begin
mdis:=mdis+1;
ddis:=d2-d1;
end
else
begin
ddis:=d2 - d1 +DaysInMonth(t1);
end;
end;
result := 30 * mdis + ddis; //计算时间差
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
memo1.Lines.Add(datetostr(dd1.Date)+' '+datetostr(dd1.Date));
memo1.Lines.Add('时间间隔:'+inttostr(daydis(dd1.Date,dd2.Date)));
memo1.Lines.Add('------------------------------------');
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
memo1.Lines.Clear;
end;
end.
这个函数大致按照你的意思写的,你试试看符合对不对
2004-2-29 2005-2-28
358
------------------------------------
2004-2-29 2005-3-1
361