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

I'm using a few methods of retreiving the time, and coming up with a date of exactly 1 month ago using each method. Here is an example of a snippet of code I'm using:

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); $year += 1900;

Now, when I run the program, I get these results: 14052002 This is exactly one month ago... I run DATE on my linux box, and it gives me the correct date. Any ideas ?

Replies are listed 'Best First'.
Re: Strange Date/Time
by kvale (Monsignor) on Jun 15, 2002 at 01:11 UTC
    The months returned from localtime are in the range 0..11, so you need to add +1 to get a human rep. This apparently weird convention comes from C, and is useful for indexing months in 0-based arrays in C and Perl. The $wday is 0-based as well. The year offset is harder to justify and IIRC this will be corrected in Perl6.

    -Mark
      Absolutely perfect... that explains everything. Thank you very much Mark !
Re: Strange Date/Time
by dws (Chancellor) on Jun 14, 2002 at 23:54 UTC
    Now, when I run the program, I get these results: 14052002 This is exactly one month ago... I run DATE on my linux box, and it gives me the correct date. Any ideas ?

    Yes. Re-read the documentation for localtime carefully. You're adding 1900 to the year, so you're close to getting it right.