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

Hi there Monks!
I know the code here will give the last month in its name, but I am trying to get it in number format, like instead of printing "November" it will print "11".
Any suggestions?
use warnings; use strict; use Time::Piece; my $t = Time::Piece->new(); my $lastmonth = $t->add_months(-1); print $lastmonth->strftime('%B'), "\n"; # Doesnt work #my $l_month_number = $lastmonth->strftime('%02d');
Thanks!

Replies are listed 'Best First'.
Re: Last month's number with Time::Piece
by Perlbotics (Archbishop) on Dec 04, 2014 at 18:40 UTC

    It's an object, you can use the method: mon()

    print $lastmonth->mon, "\n"; print "ref: ", ref $lastmonth, "\n"; print "one: ", $t->add_months(-1)->mon, "\n"; # all together

    Result:

    11 ref: Time::Piece one: 11

    Update: added ref() and example for clarification.
      That worked just fine, thanks a lot!
      To complement, with this I am trying to also get the last day of the last month, here is what I am using, it might be a shorter way as well:
      use warnings; use strict; use Time::Piece; my $t = Time::Piece->new(); my $year = $t->year; my $last_month = $t->add_months(-1)->mon; # Pass the last month and year to a new Time::Piece object my $t_last_month = Time::Piece->strptime("$last_month$year", "%m%Y"); # Now use Time::Piece month_last_day to get it my $last_day_of_month = $t_last_month->month_last_day; print "Last Month = $last_month - It's last day = $last_day_of_month \ +n";

      Thanks!
        just a short observation - to make this work correctly, add a line like this before calling strptime: if (length($last_month) == 1) { $last_month = "0" . $last_month; }