[PBP-pm] Working with dates

Jay Buffington jay at mlug.missouri.edu
Tue Dec 20 21:27:31 PST 2005


Hi Everyone.

I'd like some feedback on best practices for working with dates in
perl.  Here's what I came up with:

Date Calculations
Use CPAN's Date::Calc to do any math or comparisons of dates. See
Date::Calc's recipes
(http://search.cpan.org/dist/Date-Calc/Calc.pod#RECIPES) section for
more examples.

Example:
Determine if today date is between Dec. 12th, 2005 and Dec. 19th, 2005
(inclusive):

use Date::Calc qw( Date_to_Days Today );

my $lower = Date_to_Days(2005, 12, 12);
my $upper = Date_to_Days(2005, 12, 19);

my $date = Date_to_Days(Today());

if (($date >= $lower) && ($date <= $upper)) {
   print "Today is between Dec. 12th and Dec. 19th!\n";
}


Returning Dates from Functions
Functions or methods that need to return a date should return them in
a hash reference using the same format the DateTime module takes as
input.

Example:
Return a date that represents Tue Dec 15 19:23:45 PST 2005

return  {
           year      => 2005,
           month     => 12,
           day       => 15,
           hour      => 19,
           minute    => 23,
           second    => 45,
           time_zone => '+0800',
         };


Displaying Dates
Use CPAN's DateTime to format dates for display.

Example:
Print the date a file was uploaded as a RFC822-conformant date

use DateTime;

my $date = $file->get_upload_date();
my $dt = new DateTime( %{ $date } );
# `perldoc DateTime` for all format specifiers
print $dt->strftime('%a, %d %b %Y %H:%M:%S %z');


More information about the PBP-pm mailing list