#!/usr/bin/perl -w require 5.003; use POSIX "floor"; #-------------------------- What This Does ---------------------------- # We specify month, day, and year. This gives the name of the day of the week. # Note: Sun = 0, Jan = month 1, Jan 1 = day 1 # The idea is to compute the number of days since some reference day (I use # Jan. 1, 2000, a Saturday) and compute this Mod 7 since 7 days per week. # Unusable for dates before Sept. 14, 1752 (Gregorian Calendar reformation) # This example is intended to be clear. One can make this much shorter, # but it is then more difficult to understand. # Asks you for input. #---------------------------- Main Program ---------------------------- # The following will be useful. @DoW = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); @MoY=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); # For a leap year February needs to be corrected (done in Step 1). @MonthLength = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); print "\n Give me a date and I'll tell you the day of the week. \n\tMonth? [1,...12] "; $Month = ; chomp($Month); print "\t\t (you picked $MoY[$Month-1])\n"; print "\n\tDay? "; $Day = ; chomp($Day); print "\n\tYear? [as: 2012] "; $Year = ; chomp($Year); # Step 1: If Year is a leap year, set $MonthLength[1]=29; if ( (($Year % 4) == 0) and ( (($Year % 100) != 0) or ( ($Year % 400) == 0) ) ) { $MonthLength[1]=29; } # Compute the day number of the given date. For Feb. 2, # Day_Num = 31 + 2 = 33 while in a non-leap year, the # Day_Num of March 1 is 31 + 28 + 1 = 60. # Step 2: Compute day_number of the specified Month, Day, Year $Day_Num = 0; # Initialize for ($i=0; $i < ($Month-1); $i++) { # Days in preceding months $Day_Num = $Day_Num + $MonthLength[$i]; } $Day_Num = $Day_Num + $Day; # Add correction for current month. # Step 3: Number of _complete_ years between $Year and Jan 1, 2000 $YY = $Year - 2000; # Step 4: Number of leap years between Jan. 1, 2000 and the $Year -1 $Leap_Years_Since_2000 = floor(($YY-1)/4) -floor(($YY-1)/100) + floor(($YY-1)/400); $Days_since_Jan1_2000 = $Day_Num + $YY*365 + $Leap_Years_Since_2000; # Step 5: divide by 7 $Day_of_Week = ($Days_since_Jan1_2000 + 6) % 7; # Jan 1, 2000 was a Sat = 6 $Answer = $DoW[$Day_of_Week]; print "\n$Month/$Day/$Year is a $Answer\n"; print "\t$MoY[$Month-1] $Day, $Year is a $Answer\n"; # ================================================================= # Since everything is mod 7, the following is equivalent but shorter. # It uses $Day_Num from above but replaces steps 3, 4, and 5. print "\n\n\t(This uses the shorter version)\n"; $Y1 = $Year - 1; # previous year $Day_of_Week = ($Day_Num + $Y1 + floor($Y1/4) - floor($Y1/100) + floor($Y1/400) ) % 7; $Answer = $DoW[$Day_of_Week]; print "\t$MoY[$Month-1] $Day, $Year is a $Answer\n\n";