Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Determing Week Ranges between given date range?

by ikegami (Pope)
on Oct 12, 2010 at 16:01 UTC ( #864890=note: print w/replies, xml ) Need Help??


in reply to Determing Week Ranges between given date range?

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() ) ->add( days => 1 ); }

Replies are listed 'Best First'.
Re^2: Determing Week Ranges between given date range?
by mojotoad (Monsignor) on Oct 12, 2010 at 17:20 UTC
    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) { ($week_e = $week_s->clone())->add( 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 );
        Sort of...actually, I cribbed that code from something I had lying around -- that code was designed around the convention of 0=Mon, 1=Tue, etc. But I forgot, oops.

        After fixing that assumption, this also works (closer to the form I originally used). 0=Sun, 1=Mon ... :

        days => ($first_dow + (6 - $week_s->dow())) % 7
        Thanks for spotting it.

        Cheers,
        Matt

Re^2: Determing Week Ranges between given date range?
by Anonymous Monk on Oct 12, 2010 at 17:39 UTC
    That is perfect!
    Thanks

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://864890]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2021-01-21 18:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?