Perl: the Markov chain saw PerlMonks

### Determing Week Ranges between given date range?

 on Oct 12, 2010 at 15:07 UTC Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to calculate weekly date ranges (start and end) from a given date range (e.g. April 1, 2010 - October 10, 2010)

I'm hoping there is a module for this.

This is what I would expect to see:
```weeks between April 1, 2010 - October 10, 2010 are:
Week 1: April 1, 2010 - April 4, 2010
Week 2: April 5, 2010 - April 11, 2010
...
Is there an easy way to do this?
Thanks

Replies are listed 'Best First'.
Re: Determing Week Ranges between given date range?
by ikegami (Pope) on Oct 12, 2010 at 16:01 UTC
```use strict;
use warnings;

use DateTime qw( );

my \$s = DateTime->new(year => 2010, month =>  4, day =>  1);
my \$e = DateTime->new(year => 2010, month => 10, day => 10);

my \$week_s = \$s;
my \$week_e;
my \$week_c;
while (\$week_s <= \$e) {
# First Sunday on or after \$week_s
( \$week_e = \$week_s->clone() )
->add( days => 7 - \$week_s->dow() % 7 );

\$week_e = \$e->clone if \$week_e > \$e;

printf("Week %s: %s to %s\n",
++\$week_c,
\$week_s->strftime('%x'),
\$week_e->strftime('%x'),
);

( \$week_s = \$week_e->clone() )
}
If you want the first day of the week to be something besides Sunday, you can do this:
```  my \$dow1 = 1; # (0-7)
...
while (\$week_s <= \$e) {
days => (\$dow1 + (7 - \$week_s->dow()) % 7,
);
...

Cheers,
Matt

If you want the first day of the week to be something besides Sunday

He wants it to be Monday.

you can do this:

You have an off-by-one error.

```my \$first_dow = 1;  # 0=Sun, 1=Mon, ..., 7=Sun

...

# Day before first \$first_dow after \$week_s
->add( days => ((7 - \$week_s->dow()) + (\$first_dow + 6)) % 7 );
That is perfect!
Thanks
Re: Determing Week Ranges between given date range?
by Ratazong (Monsignor) on Oct 12, 2010 at 15:23 UTC

I would have a look at Date::Calc. It contains many functions like Day_of_Week or Monday_of_Week which might be useful for you.

HTH, Rata

Create A New User
Node Status?
node history
Node Type: perlquestion [id://864875]
Approved by Ratazong
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (11)
As of 2017-11-22 21:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In order to be able to say "I know Perl", you must have:

Results (327 votes). Check out past polls.

Notices?