slloyd has asked for the wisdom of the Perl Monks concerning the following question:

Given a dayofyear number (1-365), how can I determine what day of the week that is (Mon, Tues, ...)?

-------------------------------
Sign up now for a free monthly newsletter service!
http://www.bestgazette.com

Replies are listed 'Best First'.
Re: weekday from dayofyear
by jeffa (Bishop) on Jan 02, 2009 at 19:52 UTC

    Use DateTime

    perl -MDateTime -le'print DateTime->from_day_of_year( day_of_year => 5 +, year => 2009 )->day_name'

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: weekday from dayofyear
by ikegami (Patriarch) on Jan 02, 2009 at 19:53 UTC

    A DateTime solution:

    use DateTime qw( ); my $doy = ...; # 1-366 my $year = DateTime ->today( time_zone => 'local' ) ->year(); my $dow = DateTime ->from_day_of_year( year => $year, day_of_year => $doy, ) #->day_of_week(); # 1-7 = M-Su, or ->day_name(); # Name of day according to locale.
Re: weekday from dayofyear
by kennethk (Abbot) on Jan 02, 2009 at 19:51 UTC

    Depends on the year. For 2009, Jan 1 is a Thursday, so:

    my $day_of_year = 1; # or whatever @days_of_week = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); print $days_of_week[($day_of_year+3)%7];

    Update: fixed typo s/$dayofyear/$day_ of_year/ -- thanks ww

Re: weekday from dayofyear
by DStaal (Chaplain) on Jan 02, 2009 at 19:58 UTC

    I'll assume you know the year as well... (Otherwise you can't: It is indeterminate.) Time::Local and localtime together can get it for you:

    use Time::Local 'timelocal_nocheck'; (undef,undef,undef,undef,undef,undef,$wday,undef,undef) = localtime(ti +melocal_nocheck(0,0,0,$day_of_year,0,$year));

    (If I'm reading the docs right, that should work. It's not quite explicitly stated.)

      Time::Local is buggy when you use it to do time/date arithmetic. The maintainer refused to apply a simple harmless fix for the bug. I think this line was added to the docs instead:

      If you supply data which is not valid (month 27, second 1,000) the results will be unpredictable (so don't do that).

      He told me that Time::Local isn't to be used for date/time arithmetic. _nocheck doesn't relax the need for valid inputs. The fourth argument needs to be a valid day for the specified month and year. If it's not allowed with _nocheck, it's not allowed without.

        Which is what made me nervous. Just a few lines above that though he also gave an example which I basically just copy-and-pasted into here...

        On the one hand, everything in it is core, and according to the docs it should work. On the other, according to those same docs it may not be reliable. Depending on the situation, I might consider using it. (Where consider == test thoroughly.)