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

Hi Monks, newbie to Perl and have a little bit of a problem, but should be quite simple to work out for someone more experienced. I have a small script to work out the date last month and the year last month that looks like this:

#!/usr/bin/perl use DateTime; $dt = DateTime->now(); $month = $dt->subtract(months => 1)->strftime("%m"); $year = $dt->subtract(months => 1)->year(); print $dt."\n"; print $month."\n"; print $year."\n";

System date at time of writing is: Tue Feb 7 14:47:55 GMT 2012 which should give me a month of 01, and a year of 2012 right? So why is the output: 2011-12-07T14:47:55 01 2011 :(

Replies are listed 'Best First'.
Re: Datetime Problem - Wrong Time
by chessgui (Scribe) on Feb 07, 2012 at 15:07 UTC
    Try this:
    #!/usr/bin/perl use DateTime; $dt = DateTime->now(); $dt->subtract(months => 1); $year = $dt->year(); $month = $dt->strftime("%m"); print $dt."\n"; print $month."\n"; print $year."\n";

      Oh it subtracts twice!!! I just literally facepalmed.... Updated to:

      #!/usr/bin/perl use DateTime; $dt = DateTime->now->subtract(months => 1); $month = $dt->strftime("%m"); $year = $dt->year(); print $dt."\n"; print $month."\n"; print $year."\n";

      Works now! Thanks monks :D

        FYI, if you want to use DateTime the way you were using it, there's clone:

        #!/usr/bin/perl use DateTime; $dt = DateTime->now(); $month = $dt->clone->subtract(months => 1)->strftime("%m"); $year = $dt->clone->subtract(months => 1)->year(); print $dt."\n"; print $month."\n"; print $year."\n";
Re: Datetime Problem - Wrong Time
by Anonymous Monk on Feb 07, 2012 at 14:59 UTC
    timezone is timezone, timezone is UTC, and you're subtracting TWO months, not one, and february being the 2nd month, -2 months is last year
      $ perl -MDateTime -le " print DateTime->now()->strftime( q/%F-%H:%M:%S +%z/) " 2012-02-07-15:07:12+0000 $ perl -MDateTime -le " print DateTime->now( qw[ time_zone local ] )-> +strftime( q/%F-%H:%M:%S%z/) " 2012-02-07-07:07:15-0800