28. februar 2002 - 11:33
Der er
2 kommentarer og
1 løsning
Ligge sekunder til TDateTime
Hej jeg ønsker at ligge f.eks 10 sek, 10 min eller 1 time til en TDateTime, hvordan gør jeg det
var
StartTid :TDateTime;
procedure TForm1.FormCreate(Sender: TObject);
begin
StartTid := Now;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if StartTid + ??? f.eks 10 sekunder ??? < Now then
ShowMessage('Tiden er gået ');
end;
28. februar 2002 - 11:40
#3
Nedenstående kunne måske også bruges ;)
Question/Problem/Abstract:
How to add a just a part of date/time (eg day, minute, or month) to a TDateTime type variable.
Answer:
I found VBScript's buildin function: DateAdd() is very handy. It allows you to specify which part-of-date you wish to add.
Here's the Object Pascal version. I changed the name to DateTimeAdd() to make it more descriptive -- emphasizing that it works for DateTime instead of just Date. The original function expects a plain char type argument to specify the date part. I replaced that one with an enumeration type, ensuring the passed argument is in correct form during compile time.
I'm not going to describe VBScript's DateAdd() further. Your knowledge about that function will help a bit, but know nothing about it is completely fine.
--------------------------------------------------------------------------------
uses
..., SysUtils;
type
TDateTimePart = (dtpHour, dtpMinute, dtpSecond, dtpMS, dtpDay, dtpMonth,
dtpYear);
function DateTimeAdd(SrcDate: TDateTime; DatePart: TDateTimePart;
DiffValue: Integer): TDateTime;
implementation
function DateTimeAdd(SrcDate: TDateTime; DatePart: TDateTimePart;
DiffValue: Integer): TDateTime;
var
m, d, y: Word;
begin
case DatePart of
dtpHour: { hour }
Result := SrcDate + (DiffValue / 24);
dtpMinute: { Minute }
Result := SrcDate + (DiffValue / 1440);
dtpSecond: { Second }
Result := SrcDate + (DiffValue / 86400);
dtpMS: { Millisecond }
Result := SrcDate + (DiffValue / 86400000);
dtpDay: { Day }
Result := SrcDate + DiffValue;
dtpMonth: { Month }
Result := IncMonth(SrcDate, DiffValue);
else { Year }
begin
DecodeDate(SrcDate, y, m, d);
Result := Trunc(EncodeDate(y + DiffValue, m, d)) +
Frac(SrcDate);
end;
end; {case}
end;
--------------------------------------------------------------------------------
Sample:
var
Date3MonthsAfterNow: TDateTime;
Date2YearsAgo: TDateTime;
Date11DaysAfterNow: TDateTime;
begin
Date3MonthsAfterNow := DateTimeAdd(Now, dtpMonth, 3);
Date2YearsAgo := DateTimeAdd(Now, dtpYear, -2); // negative is OK
Date11DaysAfterNow := DateTimeAdd(Now, dtpDay, 11);
end;
Snowball