Author: Hans Gulö
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.
1 uses
2 ..., SysUtils;
3
4 type
5 TDateTimePart = (dtpHour, dtpMinute, dtpSecond, dtpMS, dtpDay, dtpMonth,
6 dtpYear);
7
8 function DateTimeAdd(SrcDate: TDateTime; DatePart: TDateTimePart;
9 DiffValue: Integer): TDateTime;
10
11 implementation
12
13 function DateTimeAdd(SrcDate: TDateTime; DatePart: TDateTimePart;
14 DiffValue: Integer): TDateTime;
15 var
16 m, d, y: Word;
17 begin
18 case DatePart of
19 dtpHour: { hour }
20 Result := SrcDate + (DiffValue / 24);
21 dtpMinute: { Minute }
22 Result := SrcDate + (DiffValue / 1440);
23 dtpSecond: { Second }
24 Result := SrcDate + (DiffValue / 86400);
25 dtpMS: { Millisecond }
26 Result := SrcDate + (DiffValue / 86400000);
27 dtpDay: { Day }
28 Result := SrcDate + DiffValue;
29 dtpMonth: { Month }
30 Result := IncMonth(SrcDate, DiffValue);
31 else { Year }
32 begin
33 DecodeDate(SrcDate, y, m, d);
34 Result := Trunc(EncodeDate(y + DiffValue, m, d)) +
35 Frac(SrcDate);
36 end;
37 end; {case}
38 end;
39
40 Sample:
41
42 var
43 Date3MonthsAfterNow: TDateTime;
44 Date2YearsAgo: TDateTime;
45 Date11DaysAfterNow: TDateTime;
46 begin
47 Date3MonthsAfterNow := DateTimeAdd(Now, dtpMonth, 3);
48 Date2YearsAgo := DateTimeAdd(Now, dtpYear, -2); // negative is OK
49 Date11DaysAfterNow := DateTimeAdd(Now, dtpDay, 11);
50 end;
|