mhearse has asked for the wisdom of the Perl Monks concerning the following question:
I've got several scripts which rely on previous calendar dates. Not just yesterday, but possibly 60, 30, etc days in the past. A typical example would be to fill a hash with the caledar dates for the past 45 days. I wrote a subrouting which works fine. If I want a date other that yesterday, I just loop through the routine for the desired number of days. Is there a module which handles this type of date calculation easily? Or a standard way of handling this in Perl? I'm just looking for input.
My subroutine accepts a date such as 2005-03-01, and returns the previous date, similarly formatted.
sub get_yesterday { my $date = shift; my ($year, $month, $day) = split/-/,$date; $month--; my @days_per_month = qw(31 28 31 30 31 30 31 31 30 31 30 31); if (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0) { $days_per_month[1] = '29'; } if ($day == 1) { if ($month == 0) { $month = '11'; $year--; } else { $month--; } $day = $days_per_month[$month]; } else { $day--; } $month++; for ($year, $month, $day) { if (/\b\d{1}\b/) { $_ = "0$_"; } } return "$year-$month-$day"; }
|
---|
Back to
Seekers of Perl Wisdom