[PBP-pm] Working with dates

David Wheeler david at kineticode.com
Wed Dec 21 10:45:59 PST 2005


On Dec 20, 2005, at 9:27 PM, Jay Buffington wrote:

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

One word: DateTime:

   http://search.cpan.org/dist/DateTime/

It's not the fastest, but it is by far the most accurate date and  
time module you can find.

> 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";
> }

my $lower = DateTime->new(
    year  => 2005,
    month => 12,
    day   => 12,
);
my $upper = DateTime->new(
    year  => 2005,
    month => 12,
    day   => 19,
);

my date = DateTime->now;
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',
>          };

Why not just return a DateTime object? Also, avoid offsets, as time  
zones with the same offsets can actually have a great deal of variation.

> 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');

Yep!

Best,

David


More information about the PBP-pm mailing list