Manipulating date data in perl

Here are some notes on doing all sorts of fun things with dates in perl.

Keeping in mind that there’s always more than one way to do it in perl, I’ve decided to do a brain dump here of some date manipulation techniques I’ve picked up along the way.

Parsing day, month year using localtime

($day, $month, $year) = (localtime)[3,4,5];
$month = $month + 1;
$year = $year + 1900;

Localtime begins counting months at 0 (for January), and only provides 3 digit dates (so “2011” comes across as “111”). Also, leading zeros are not provided for month or day values, so if you want a string like “20110317”, you’ll need to do something like:

$today = sprintf("%04%02%02", $year, $month, $day);

Parsing the same with Date::Calc

use Date::Calc qw(Today);
($year, $month, $day) = Today();

Again, with Date::Calc leading zeros aren’t provided so you’ll need to reformat the values if you want them. The module’s Today function is a nice alternative to localtime.

Comparing Dates using Date::Calc

use Date::Calc qw(Date_to_Days);
if (Date_to_Days($year1, $month1, $day1) < Date_to_Days($year2, $month2, $day2)) {

# Do something here

}

Date_to_Days, like other functions provided by Date::Calc, will choke on a date elements with a leading zero. In fact, when using these methods always be sure to validate that.

Removing leading zeros from date elements

To ensure that you’re not passing date elements with leading zeros to Date::Calc or other modules, you can redefine those values using perl’s int function:

$month = int $month;
$day = int $day;