Calculate day of the week for a given date MM-DD-YYYY

KevinADC 1 Tallied Votes 1K Views Share

Given the date in mm-dd-yyyy (or M-D-YYYY) format (or any combination of that format) you can find out what day of the week that was on or is on or will be on, within the limitations of the system the script resides on.

This snippet uses only core functions and modules so nothing needs to be installed but it is worth mentioning that there are numerous date modules on CPAN that offer a wide range of functions for handling date calculations.

This snippet assumes the date is in mm-dd-yyyy format but can easily be adapted to handle any combination of those date parameters. Can also handle years in three digit and two digit format but see the Time::Local and localtime() documentation for limitations.

leo002000 commented: 3 +3
use Time::Local 'timelocal_nocheck';

# An array to hold the names of each day of the week. 
my @weekday = qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday);

# '09-11-2001' can be a parameter/argument you pass to the script
my $mm_dd_yyyy = '09-11-2001';
my $day_of_week = get_day($mm_dd_yyyy);
print "$mm_dd_yyyy was a $day_of_week";

sub get_day {
   my $date = shift || return(0); 
   my ($mon,$mday,$year) = $date =~ /(\d+)-(\d+)-(\d+)/;
   my $epochtime = timelocal_nocheck(0, 0, 0, $mday, $mon-1, $year);
   my $day = (localtime($epochtime))[6];
   return $weekday[$day];