Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: What is the best way to get a list of all Mondays until the end of the year?

by Rhandom (Curate)
on Aug 19, 2008 at 16:14 UTC ( #705253=note: print w/replies, xml ) Need Help??

in reply to What is the best way to get a list of all Mondays until the end of the year?

Golfing - with no modules:
perl -e '@N=gmtime;$t=time+86400*(1-$N[6]);while(1){@n=gmtime($t+=7*86 +400);last if $n[5]!=$N[5]; printf("%d-%02d-%02d\n",$n[5]+1900,$n[4]+1 +,$n[3])}'
Human readable and explained:
perl -e ' my @N = gmtime; # today (calculations in gmtime to avoid tz offset +s) my $t = time + 86400 * (1 - $N[6]); # calculate the time of Monday +(1) while(1) { my @n = gmtime($t += 7*86400); # advance a week at a time last if $n[5] != $N[5]; # done if the year doesn't mat +ch today's printf ("%d-%02d-%02d\n", $n[5]+1900, $n[4]+1, $n[3]); # print re +sult }'

Really you should look at DateTime or Date::Manip or Date::Calc or ... - but sometimes it makes sense not to.
my @a=qw(random brilliant braindead); print $a[rand(@a)];

Replies are listed 'Best First'.
Re^2: What is the best way to get a list of all Mondays until the end of the year?
by Krambambuli (Curate) on Aug 19, 2008 at 16:27 UTC
    Just a side node; this would work most of the time, but not always. A week is _not_ always 7*86400 seconds, a day is _not_ always 86400 seconds - when daylight saving comes to play, this offset may give you a false Monday (if you're making the calculation at a unwise chosen time ;) )

    Update: daylight saving changes.

      What you say is true for localtime, but not for gmtime (which is what the Rhandom's example uses). As the doc says, there is no DST for GMT.
        Sure - but the Mondays we're interested in would probably need to be in local timezone and DST, not GMT. I'm not really sure the code would fail, but I wouldn't bet I get the correct list of dates regardless when the calculation is done either.

        I'm not sure the back-and-forth between localtime and gmtime works OK for this calculation - but consider that the Mondays surrounding a DST change date are 7*86400 +- 3600 seconds apart in 'real life' - using 7*86400 instead might place me a day ahead or behind if I'm somehwere near midnight when making the calculation.

        Just a warning about the not-at-all-trivial datetime calculations.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://705253]
[choroba]: Good morning from home!
[choroba]: (took a sickday to stay with my son)

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2017-04-27 07:43 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (501 votes). Check out past polls.