How to create an array of dates between a start and end date in Pascal

1 Answer

0 votes
program DateRangeProgram;

type
  Date = record
    Year  : Integer;
    Month : Integer;
    Day   : Integer;
  end;

const
  MAX_DATES = 500;  

var
  StartDate, EndDate : Date;
  Dates : array[1..MAX_DATES] of Date;
  Count : Integer;

{---------------------------------------------}
function IsLeapYear(Y: Integer): Boolean;
begin
  IsLeapYear := (Y mod 4 = 0) and ((Y mod 100 <> 0) or (Y mod 400 = 0));
end;

{---------------------------------------------}
function DaysInMonth(Y, M: Integer): Integer;
begin
  case M of
    1,3,5,7,8,10,12: DaysInMonth := 31;
    4,6,9,11:        DaysInMonth := 30;
    2: if IsLeapYear(Y) then DaysInMonth := 29 else DaysInMonth := 28;
  else
    DaysInMonth := 0;
  end;
end;

{---------------------------------------------}
function NextDate(D: Date): Date;
begin
  D.Day := D.Day + 1;
  if D.Day > DaysInMonth(D.Year, D.Month) then
  begin
    D.Day := 1;
    D.Month := D.Month + 1;
    if D.Month > 12 then
    begin
      D.Month := 1;
      D.Year := D.Year + 1;
    end;
  end;
  NextDate := D;
end;

{---------------------------------------------}
function DateLessOrEqual(A, B: Date): Boolean;
begin
  if A.Year < B.Year then DateLessOrEqual := True
  else if A.Year > B.Year then DateLessOrEqual := False
  else if A.Month < B.Month then DateLessOrEqual := True
  else if A.Month > B.Month then DateLessOrEqual := False
  else DateLessOrEqual := A.Day <= B.Day;
end;

{---------------------------------------------}
procedure AddDateToArray(D: Date);
begin
  Count := Count + 1;
  Dates[Count] := D;
end;

{---------------------------------------------}
procedure PrintDate(D: Date);
begin
  WriteLn(D.Year, '-', D.Month, '-', D.Day);
end;

{---------------------------------------------}
var
  Current : Date;
  I       : Integer;

begin
  { Initialize start and end dates }
  StartDate.Year  := 2026;
  StartDate.Month := 1;
  StartDate.Day   := 3;

  EndDate.Year  := 2026;
  EndDate.Month := 1;
  EndDate.Day   := 12;

  Count := 0;
  Current := StartDate;

  while DateLessOrEqual(Current, EndDate) do
  begin
    AddDateToArray(Current);
    Current := NextDate(Current);
  end;

  { Print results }
  for I := 1 to Count do
    PrintDate(Dates[I]);
end.




(*
run:

2026-1-3
2026-1-4
2026-1-5
2026-1-6
2026-1-7
2026-1-8
2026-1-9
2026-1-10
2026-1-11
2026-1-12

*)


 



answered Jan 30 by avibootz
...