Perl Advent Calendar 2006-12-20

Counting down the days…

by David Westbrook

Date::Calc is a toolkit of over sixty date and time functions from simple date math to Easter calculations. It can prove to be a nice, light-weight alternative to DateTime, or the plethora of other Date modules out there. Implemented as a C library with XS wrapper Date::Calc lives up to its motto of, "Keep it small, fast and simple"; there are no default exports. The module is "fun for everyone" and ships with support for over a dozen languages.

The wait is almost over…

What month is it?

use Date::Calc qw/Decode_Language Language Month_to_Text/;
foreach my $lang (qw/English Français Deutsch Español Português Nederlands
                      Italiano Norsk Svenska Dansk suomi Magyar Polski/){
  Language( Decode_Language( $lang ) );
  printf "%10s: %s\n", $lang, Month_to_Text( 12 );

When's Christmas?

How much longer do we have to wait?!?

use Date::Calc qw/Today Delta_Days/;
printf "Christmas is %d days away", Delta_Days( Today(), 2006, 12, 25 );

What if it's after 2006-12-25? What about 'next' Christmas, no matter what the current year is?

use Date::Calc qw/Today Delta_Days Add_Delta_YMD/;
my @next_Christmas = ( (Today)[0], 12, 25 );
if( Delta_Days( Today(), @next_Christmas ) < 0 ){
  # in case we past this year's holiday already, e.g. it's 12/28
  @next_Christmas = Add_Delta_YMD( @next_Christmas, 1, 0, 0 );
printf "Christmas is %d days away", Delta_Days( Today(), @next_Christmas );

Fancy Trimmings

In addition to providing functions for date calculation, like finding last Monday:
$ perl -MDate::Calc=:all -e 'printf "%04d%02d%02d", Monday_of_Week( Week_of_Year(Today) )'
You can also verify that a date is well formed:
use Date::Calc qw/check_date/;
my $s = '2006-12-01';
print "OK" if check_date( split(/-/,$s) );
And even produce a cal like calendar (single month mode only):
$ perl -MDate::Calc=:all -e 'print Calendar( 2006, 12 )'

         December 2006
  Mon Tue Wed Thu Fri Sat Sun
                    1   2   3
    4   5   6   7   8   9  10
   11  12  13  14  15  16  17
   18  19  20  21  22  23  24
   25  26  27  28  29  30  31

Tasty Recipes

Better than fruitcake or mincemeat pie are the 17 recipes included in the Date::Calc documentation, covering topics such as printing dates as strings (e.g. 'Monday, December 25th, 2006'), checking someone's age, finding a pay date, converting a MS Visual Basic "DATETIME" value, and working with date ranges.