AddCalendarMonths Function
Adds a Specified Number of Calendar Months to a Given Date/Time.

Unit
QESBPCSDateTime

Declaration
Function AddCalendarMonths(const DT: TDateTime; const Months: Integer): TDateTime;

Description
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 Routines

Implementation

function AddCalendarMonths (const DT: TDateTime; const Months: Integer): TDateTime;
var
     Day, Month, Year: Integer;
     IMonth: Integer;
begin
     OptDecodeDateI (DT, Year, Month, Day);
     IMonth := Month + 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 (DT);
End;


HTML generated by Time2HELP
http://www.time2help.com