Working with dates is a common enough task and Perl comes with a couple of built-in functions for lower level date calculations (localtime() and gmtime()) and a Time::Local module which provides complementary functions (timelocal() and timegm()). However, for doing higher level date calculations you’ll want to grab either the Date::Manip or Date::Calc modules from CPAN.
The Date::Manip module is pure Perl (so it’ll install and run anywhere you have Perl) and is quite large. The Date::Calc module uses a C library so you’ll need to compile your own or get a prebuilt version (activestate has a version for win32). Date::Calc is leaner, much faster, and probably the one you want to work with (we’ll use it in the examples here).
The Date::Calc module contains a large number of convenience routines such as: Day_of_Year(), check_date(), leap_year(), Delta_Days(), Date_to_Text(), and too many more to list. For example, to check to see if a given date is valid:
use Date::Calc qw/check_date/;
print "Bad Date\n" unless check_date(2001, 9, 31);
This tells us that the date is bad because there is no September 31st. We can calculate the difference between two dates with the Delta_Days function:
use Date::Calc qw/Delta_Days/;
my ($year1, $month1, $day1) = (2001, 2, 8);
my ($year2, $month2, $day2) = (2001, 12, 25);
my $delta = Delta_Days($year1, $month1, $day1,
$year2, $month2, $day2);
print "Only $delta more days until Christmas!\n";
Have you been told your invoice will be paid in 45 days and want to circle that date on your calendar?
use Date::Calc qw/Add_Delta_Days Date_to_Text_Long/;
my ($year, $month, $day) = (localtime())[5,4,3];
$year += 1900;
$month++;
print "Enter number of days from today: ";
chomp(my $ddays = <STDIN>);
my $date = Date_to_Text_Long(
Add_Delta_Days($year, $month, $day, $ddays)
);
print "$date is $ddays from today\n";
You can also get or add deltas with hours, minutes, and seconds for more precise calculations. And, of course, there is a good deal more functionality in the Date::Calc, and the Date::Manip modules than I’ve highlighted here.
Working with dates isn’t hard, but it also isn’t hard to work with them incorrectly — using one of the Date modules helps you avoid mistakes and often greatly simplifies your task.
*****



