program MonthsBetweenExample;
{$mode objfpc}{$H+}
uses
SysUtils;
{
Returns the number of complete months between two dates.
Examples:
2026-01-15 -> 2027-07-20 = 18
2026-01-15 -> 2027-07-14 = 17
}
function GetMonthsBetween(startdate, enddate: TDateTime): Integer;
var
StartYear, StartMonth, StartDay: Word;
EndYear, EndMonth, EndDay: Word;
begin
{ Extract year, month, and day components }
DecodeDate(startdate, StartYear, StartMonth, StartDay);
DecodeDate(enddate, EndYear, EndMonth, EndDay);
{ Calculate the raw month difference }
Result :=
(EndYear - StartYear) * 12 +
(EndMonth - StartMonth);
{ If the end day is before the start day,
the last month is not complete }
if EndDay < StartDay then
Dec(Result);
end;
var
startdate: TDateTime;
enddate: TDateTime;
months: Integer;
begin
{ YYYY, MM, DD }
startdate := EncodeDate(2026, 1, 15);
enddate := EncodeDate(2027, 7, 20);
months := GetMonthsBetween(startdate, enddate);
WriteLn('Months between dates: ', months);
end.
(*
run:
Months between dates: 18
*)