in reply to Calculating holidays

how do I parse a date

Personally I like DateTime::Format::Strptime because it lets you define exactly the expected input format.

figure out if it is the 4th Thursday of the month

( $datetime->dow==4 && $datetime->weekday_of_month==4 )

Putting that together:

use DateTime::Format::Strptime; my $strp = DateTime::Format::Strptime->new( pattern => '%Y-%m-%d', time_zone=>'UTC', on_error=>'croak' ); my $dt = $strp->parse_datetime('2017-11-23'); my $is_thanksgiving = $dt->month==11 && $dt->dow==4 && $dt->weekday_of_month==4;

As for determining the date of Thanksgiving, I agree with choroba that the best thing to do is use an existing module. But just to demonstrate one way to do a calculation like that:

sub thanksgiving { my $year = shift; my $dt = DateTime->new(year=>$year,month=>11,day=>1); $dt->add(days=>1) while $dt->dow!=4; $dt->add(weeks=>3); return $dt; }

(Tested against data from Wikipedia for the years 2000 to 2399.)

Replies are listed 'Best First'.
Re^2: Calculating holidays
by Anonymous Monk on Jul 26, 2017 at 13:28 UTC
    I'd probably write the thanksgiving function like this, because the keep-adding-one pattern gives me the jibblies.
    my $dt = DateTime->new(year=>$year, month=>11, day=>22); $dt->add(days=>(4 - $dt->dow())%7);

      Yes, that's a good point, the loop isn't very elegant. Personally I still like to anchor things at the beginning or end of the month, so I might write:

      my $dt = DateTime->new(year=>$year, month=>11); $dt->add( days=>(4-$dt->dow())%7, weeks=>3 );

      (But that's just getting nitpicky ;-) )