萧
萧月禾
Unregistered / Unconfirmed
GUEST, unregistred user!
哦,我明白我错在什么地方了,多谢杜兄提点
你才是正确的[]
你才是正确的[]
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure DateTimeDiff(St, Et: TDateTime; out Y, M, D, H, N, S, MS: Word);
var
Form1: TForm1;
implementation
uses DateUtils;
var
BeginTime: TDateTime;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
BeginTime := Now;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
Y, M, D, H, N, S, MS: Word;
begin
DateTimeDiff(BeginTime, Now, Y, M, D, H, N, S, MS);
Edit1.Text := Format('已运行 %d 年 %d 月 %d 日 %d 小时 %d 分 %d 秒 %d 毫秒',
[Y, M, D, H, N, S, MS]);
end;
procedure DateTimeDiff(St, Et: TDateTime; out Y, M, D, H, N, S, MS: Word);
var
SYear, SMonth, SDay, SHour, SMin, SSec, SMSec: Word; // 开始时间
EYear, EMonth, EDay, EHour, EMin, ESec, EMSec: Word; // 结束时间
DYear, DMonth, DDay, DHour, DMin, DSec, DMSec: Integer; // 时差
EDate: TDateTime; // 中间变量
i: Integer; // 中间变量,记录时差间隔。
procedure InitVars;
begin
DecodeDateTime(EDate, EYear, EMonth, EDay, EHour, EMin, ESec, EMSec);
end;
begin
if St > Et then // 参数出错
begin
EDate := St; // 交换起止时间
St := Et;
Et := EDate;
end;
// 变量初始化。
DecodeDateTime(St, SYear, SMonth, SDay, SHour, SMin, SSec, SMSec);
EDate := Et;
InitVars;
// 进位的加减,不足则借位。
// 从最低位开始,先来毫秒位:
DMSec := EMSec - SMSec; // 取毫秒位差
if DMSec < 0 then
begin
DMSec := 1000 + DMSec;
EDate := IncSecond(EDate, -1); // 借位
InitVars; // 改变量
end;
DSec := ESec - SSec; // 取秒位差
if DSec < 0 then
begin
DSec := 60 + DSec;
EDate := IncMinute(EDate, -1);
InitVars;
end;
DMin := EMin - SMin; // 取分钟差
if DMin < 0 then
begin
DMin := 60 + DMin;
EDate := IncHour(EDate, -1);
InitVars;
end;
DHour := EHour - SHour; // 取小时差
if DHour < 0 then
begin
DHour := 24 + DHour;
EDate := IncDay(EDate, -1);
InitVars;
end;
DDay := EDay - SDay; // 取天差,这里就复杂了!
if DDay < 0 then
begin
DDay := DaysInMonth(SDay) - SDay + EDay; // 到月底再加
EDate := IncMonth(EDate, -1);
InitVars;
end;
DMonth := EMonth - SMonth ; // 取月差
if DMonth < 0 then
begin
DMonth := 12 + DMonth;
EDate := IncYear(EDate, -1);
InitVars;
end;
DYear := EYear - SYear; // 取年差
Assert(DYear >= 0, '应该不可能小于0!');
Y := DYear; M := DMonth; D := DDay;
H := DHour; N := DMin; S := DSec; MS := DMSec;
end;
end.