Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Determining the dayname for the last day of any given month

by davorg (Chancellor)
on Jun 19, 2006 at 11:30 UTC ( #556229=note: print w/ replies, xml ) Need Help??


in reply to Determining the dayname for the last day of any given month

Using only Perl standard modules:

use strict; use warnings; use Time::Local; use POSIX 'strftime'; while (1) { print "Enter year (yyyy) and month (mm), separated by a space: "; chomp(my $input = <STDIN>); last if !$input; next unless $input =~ /(\d{4})\s+(\d\d?)/; my ($year, $month) = ($1, $2); my ($y, $m) = ($year, $month); $y -= 1900; if ($m == 12) { $m = 0; ++$y; } my $first = timelocal(0, 0, 0, 1, $m, $y); my $last = $first - 24*60*60; print "The last day of $month/$year will be a ", strftime('%A', localtime $last), "\n"; }
--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg


Comment on Re: Determining the dayname for the last day of any given month
Download Code
Re^2: Determining the dayname for the last day of any given month
by ikegami (Pope) on Jun 20, 2006 at 15:40 UTC

    Not all days are 24*60*60 seconds long, and $m suffers from off-by-one errors. Fix:

    my ($y, $m) = ($year-1900, $month-1); # Day before the first of next month: my $last = timelocal_nocheck(0, 0, 0, 1-1, $m+1, $y);

    You'll need to import timelocal_nocheck from Time::Local

    Updated. However, the fixed code doesn't work because timelocal_nocheck doesn't handle $m+1 as I expect.

      Not all days are 24*60*60 seconds long

      Well the ones on the first of the month all are :)

      But you're right, they aren't guaranteed to _always_ be. The easiest fix is probably to change the call to timelocal so it uses midday rather than midnight.

      $m suffers from off-by-one errors

      I don't think it does. The value you get from the user is in the range 1-12. We want the next month, but timelocal wants the number in the range 0-11. So we already have the correct number (except we need to do some adjustment if the month is 12). It might not be the clearest algorithm in the world, but it _is_ correct.

      --
      <http://dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

        We want the next month

        Duh! Of course!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (12)
As of 2015-07-02 09:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (33 votes), past polls