Mega Code Archive

 
Categories / Delphi / Functions
 

AdvanceDateByOneMonth function + DaysInMonth

Title: AdvanceDateByOneMonth function + DaysInMonth Question: Need a function to advance a date by one month, taking into account going from the last day of a 30 day month to the last day of a 31 day month, and visa versa, and February? This is a simple function, but hopefully it will help someone. Answer: function daysInMonth(iMonth, iYear: Integer): Integer; begin if iMonth in [1,3,5,7,8,10,12] then Result := 31 else if (iMonth in [4,6,9,11]) then Result := 30 else if isLeapYear(iYear) then Result := 29 else Result := 28; end; // daysInMonth function advanceDateByOneMonth(dd: TDateTime): TDateTime; var iYear, iMonth, iDay, iOldMonth, iOldYear: Word; begin DecodeDate(dd, iYear, iMonth, iDay); iOldMonth := iMonth; iOldYear := iYear; Inc(iMonth); if iMonth = 13 then begin iMonth := 1; Inc(iYear); end; {if last day of month is used then make the next date the last day of next month} if daysInMonth(iOldMonth, iOldYear) = iDay then iDay := daysInMonth(iMonth, iYear); Result := EncodeDate(iYear, iMonth, iDay); end; // advanceDateByOneMonth