How to find the day of the week on any given date in Pascal

1 Answer

0 votes
program ZellerPascal;

{$mode objfpc}{$H+}

// Zeller's Congruence implementation
// Returns the day of the week for a given date.
function dayOfWeek(d, m, y: Integer): String;

  // Zeller's output mapping:
  // 0 = Saturday, 1 = Sunday, 2 = Monday, ... 6 = Friday
const
  names: array[0..6] of String = (
    'Saturday', 'Sunday', 'Monday', 'Tuesday',
    'Wednesday', 'Thursday', 'Friday'
  );

var
  K, J: Integer;

  // Zeller's formula (clearer step-by-step version):
  term1, term2, term3, term4, term5, term6: Integer;

  h: Integer;

begin
  // In Zeller's formula, January and February are counted
  // as months 13 and 14 of the previous year.
  if m < 3 then
  begin
    m := m + 12;   // Convert Jan → 13, Feb → 14
    y := y - 1;    // Move to previous year
  end;

  K := y mod 100;   // Year of the century (last two digits)
  J := y div 100;   // Zero-based century (e.g., 2024 → 20)

  // Zeller's formula (clearer step-by-step version):

  term1 := d;                       // day of month
  term2 := (13 * (m + 1)) div 5;    // month adjustment
  term3 := K;                       // year of century
  term4 := K div 4;                 // leap years in century
  term5 := J div 4;                 // leap centuries
  term6 := 5 * J;                   // century correction

  // Combine all terms and take modulo 7
  h := (term1 + term2 + term3 + term4 + term5 + term6) mod 7;

  // Return the corresponding weekday name
  Result := names[h];
end;

var
  d, m, y: Integer;

begin
  d := 30;
  m := 5;
  y := 2024;

  WriteLn(dayOfWeek(d, m, y));
end.


(*
run:

Thursday

*)

 



answered 9 hours ago by avibootz
edited 9 hours ago by avibootz
...