Yesterday’s Date in Perl

You want to know what the date was yesterday (or tomorrow, or in seven days time). Last updated 2008-07-09.

This sounds like a deceptively simple problem, just subtract one from the day, e.g. that returned by localtime. This runs into immediate problems at any month or year boundaries: at the beginning of the month your day of the month will become zero, then negative.

You can get around these problems by obtaining the time in epoch seconds, subtracting the relevant number of seconds, and converting it to the format you want with localtime:

# subtract secs in day from current epoch time
my $epochYesterday = time - 24 * 60 * 60;  

# Find date of yesterday, [5,4,3] selects the year, 
#	 month and day from the list returned by localtime
my ($year, $month, $day) = (localtime($epochYesterday))[5,4,3];

# Perl years begin at 1900
$year += 1900;

# Perl months begin at 0

print "Yesterday was $year-$month-$day.\n";

This procedure can easily be extended to finding tomorrow or subtracting/adding weeks, and the calculation can be done as a one liner, for example in 7 days the date will be:

my ($year, $month, $day) = (localtime(time + 7 * 24 * 60 * 60))[5,4,3];

Download public domain sample script: yesterday_date.pl.

NB. This technique will produced undefined results outside the Unix epoch range: circa 1901 - 2038. This technique assumes all days have 24 * 60 * 60 seconds; actual days may be shorter or longer due to daylight saving time changes and leap seconds.

Tags: Date, HowTo, Perl, Time