读书人

求两个时间相差返回年月日应该怎么写

发布时间: 2013-03-20 15:25:24 作者: rapoo

求两个时间相差,返回年月日应该如何写啊?
做个假设:
时间1:1991年2月15日
时间2: 2013年3月16日

希望得到两个时间的差距值,并以年月日返回。
[解决办法]
这是你要的效果吗?


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.

读书人网 >.NET

热点推荐