good chemistry is complicated,and a little bit messy -LW PerlMonks

### Calc last friday of month

by csarid (Sexton)
 on Feb 03, 2009 at 04:37 UTC 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.");

CountZero

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) {
print "First Monday of January: ", \$dt1->ymd, "\n" and last
if \$dt1->day_of_week == 1;
}

hth,
PooLpi

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

Create A New User
Node Status?
node history
Node Type: perlquestion [id://740897]
Approved by ikegami
help
Chatterbox?
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
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
World peace can best be achieved by:

Results (193 votes). Check out past polls.

Notices?