2008. április 8., kedd

Adding a datetime part to a TDateTime type variable


Problem/Question/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;

Nincsenek megjegyzések:

Megjegyzés küldése