Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Calc last friday of month

by csarid (Sexton)
on Feb 03, 2009 at 04:37 UTC ( #740897=perlquestion: print w/replies, xml ) Need Help??
csarid has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I would like to know if perl has a way to calculate the "first monday of the month" or the "last friday of the month" etc.. Thanks!

Replies are listed 'Best First'.
Re: Calc last friday of month
by Your Mother (Bishop) on Feb 03, 2009 at 04:50 UTC
Re: Calc last friday of month
by ikegami (Pope) on Feb 03, 2009 at 04:50 UTC
    1. Find the day of the week of the first day of the month (using Date::Calc, DateTime, localtime or whatever).

    2. Find the number of days to add or subtract.

      Days to first Monday:

      $days_to_first_monday = ($dow + 7 - 1) % 7;

      Days to previous Friday:

      $days_to_last_friday = ($dow + 7 - 5) % 7 - 7;

      In both case, $dow is expected to hold 1..7 for Mon..Sun or 0..6 for Sun..Sat

    3. Use Date::Calc or DateTime to perform the math.

Re: Calc last friday of month
by CountZero (Bishop) on Feb 03, 2009 at 06:24 UTC
    use strict; use Date::Manip; $main::TZ= 'GMT'; print UnixDate(ParseDate("last Friday in February 2009"),"Last Friday +of the month is %B %E, %Y.");


    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      Wow! the Date::Manip is powerful, this is exactly what I was looking for. Thanks to every for their replies. I will definitely use the methods suggested at some point. Thanks very much!
Re: Calc last friday of month
by poolpi (Hermit) on Feb 03, 2009 at 09:03 UTC

    Some examples :

    #!/usr/bin/perl use strict; use warnings; use DateTime; my $dt = DateTime->last_day_of_month( year => 2009, month => 2 ); while ( $dt->mday() >= 1 and $dt->month == 2 ) { $dt->subtract( days => 1 ); print "Last Friday of February: ", $dt->ymd, "\n" and last if $dt->day_of_week == 5; } my $dt1 = DateTime->new( year => 2009, month => 1, day => 1 ); while (1) { $dt1->add( days => 1 ); print "First Monday of January: ", $dt1->ymd, "\n" and last if $dt1->day_of_week == 1; }


    'Ebry haffa hoe hab im tik a bush'. Jamaican proverb

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://740897]
Approved by ikegami
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2018-05-26 11:08 GMT
Find Nodes?
    Voting Booth?