| AddMonths Function |
Unit
QESBPCSDateTime
Declaration
Function AddMonths(const DT: TDateTime; const Months: Extended): TDateTime;
Description
Fractional portion of Month is assumed to be related to 30 day months. Time portion preserved.
If adding Months results in landing on a nonsense date like 31 Apr then the last day in the month is used. This only applies to the integral component of the Months Added. The fractional part always is added to the resultant Date/Time.
| Parameters |
| DT | Date/Time to process. |
| Months | Number of Months to Add - can be negative. |
Category
Date/Time Arithmetic Routines
Month Based Arithmetic RoutinesImplementation
function AddMonths (const DT: TDateTime; const Months: Extended): TDateTime;
var
Day, Month, Year: Integer;
IMonth: Integer;
begin
OptDecodeDateI (DT, Year, Month, Day);
IMonth := Month + Trunc (Months);
if IMonth > 12 then
begin
Year := Year + (IMonth - 1) div 12;
IMonth := IMonth mod 12;
if IMonth = 0 then
IMonth := 12;
end
else if IMonth < 1 then
begin
Year := Year + (IMonth div 12) - 1; // sub years;
IMonth := 12 - abs (IMonth) mod 12;
end;
Month := IMonth;
// Ensure Day of Month is valid
if Month = 2 then
begin
if IsLeapYear (Year) and (Day > 29) then
Day := 29
else if not IsLeapYear (Year) and (Day > 28) then
Day := 28;
end
else if (Month in [9, 4, 6, 11]) and (Day = 31) then
Day := 30;
Result := OptEncodeDateI (Year, Month, Day) + Frac (Months) * 30 +
Frac (DT);
End; |
|
|