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

Hi Monks, I have this peice of code which should take the current date and add 14 days on to it:
#Take Current System Date And Add Two Weeks On For Trial use constant WEEK => 60 * 60 * 24 * 7 ; my @later = localtime( time + ( WEEK * 2 ) ) ; my $expiry_date = sprintf "%04d-%02d-%02d", $later[5] + 1900, $later[4], $later[3] ;
It functions ok for adding 14 days to the current date, but it seems to deduct 1 month from the current date also. i.e if the date is 2002-02-02 it will change it to 2002-01-16 any ideas where i am going wrong? Thanks

Replies are listed 'Best First'.
Re: Adding To Dates
by DamnDirtyApe (Curate) on Aug 13, 2002 at 16:07 UTC
    perldoc -f localtime

    localtime returns 0..11 to represent the months. So, just use $later[4] + 1 in your sprintf statement instead.

    Update: Incidentally, Date::Calc gives you a very clean way to do this.

    use Date::Calc qw( Today Add_Delta_Days ) ; my $expiry_date = sprintf "%04d-%02d-%02d", Add_Delta_Days( Today, 14 +) ;

    _______________
    DamnDirtyApe
    Those who know that they are profound strive for clarity. Those who
    would like to seem profound to the crowd strive for obscurity.
                --Friedrich Nietzsche
      thanks peeps. I should have spotted that. I would use the Date::Calc to do it, but i wanted to do it without additional modules
Re: Adding To Dates
by adrianh (Chancellor) on Aug 13, 2002 at 16:19 UTC

    Your problem is that you're misinterpreting the month number returned by localtime. The index starts at 0, not 1. It's not deducting a month, you should be adding one on when you display it! See localtime for more info.

    You should also take a look at Date::Manip and the other Date:: modules in CPAN because they will save you a lot of effort :-)