in reply to Re: Month Dates
in thread Month Dates

It's odd that $month starts 0-based and ends 1-based. You also assume $monthsback is a small number. Fix:

use POSIX qw( floor strftime ); my $monthsback = 3; # 0=this month -1=last, -2, ... my ($day,$mon,$year) = (localtime())[3,4,5]; $mon -= $monthsback; $year += floor($mon / 12); $mon = $mon % 12; print(strftime("%Y-%m", 0,0,0, $day,$mon,$year), "\n");

A more general solution:

use POSIX qw( floor strftime ); my $mon_delta = -3; # ..., -2, -1=last, 0=this month +1=next, +2, ... my ($day,$mon,$year) = (localtime())[3,4,5]; $mon += $mon_delta; $year += floor($mon / 12); $mon = $mon % 12; print(strftime("%Y-%m", 0,0,0, $day,$mon,$year), "\n");

Replies are listed 'Best First'.
Re^3: Month Dates
by hangon (Deacon) on Mar 02, 2007 at 02:01 UTC

    You're rigorous as usual ikegami, your realname wouldn't be Spock? ;)

    My point is that a simple algorithm could be used instead of importing a module, but I should have specified it's parameters more thoroughly:

    # positive integer, current year my $year = # integer 1 to 12, current month my $month = # positive integer, number of months to go back my $monthsback =