http://www.perlmonks.org?node_id=542167

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

hi,

I have this following code that produces today's date in the following format YYYY-MM-DD

however, this code prints today's date as: 2006-4-9 and NOT 2006-04-09

what can I do to my script so that the date has 0's?
my $time = time; my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yd +ay,$isdst) = localtime($time); $mon++; $year += 1900; my $date = "$year-$mon-$mday";
thanks!

Replies are listed 'Best First'.
Re: Date displaying the 0's
by borisz (Canon) on Apr 09, 2006 at 19:02 UTC
    my $date = sprintf ("%04d-%02d-%02d", $year, $mon, $mday);
    Boris
Re: Date displaying the 0's
by graff (Chancellor) on Apr 10, 2006 at 00:10 UTC
    And given how sprintf takes args, you can reduce your 5 lines to just these two (taking advantage of localtime's default behavior, using an array slice on that, and doing the arithmetic in the sprintf call):
    my ( $mday, $mon, $year ) = (localtime())[3..5]; my $date = sprintf("%04d-%02d-%02d", $year+1900, $mon+1, $mday);
Re: Date displaying the 0's
by eXile (Priest) on Apr 10, 2006 at 00:42 UTC
    Or have a CPAN module do all the error-prone date-handling for you. For instance DateTime
    use DateTime $date = DateTime->now()->ymd();
Re: Date displaying the 0's
by jwkrahn (Abbot) on Apr 10, 2006 at 02:40 UTC
    use POSIX 'strftime'; my $date = strftime '%Y-%m-%d', localtime;
Re: Date displaying the 0's
by sen (Hermit) on Apr 10, 2006 at 04:29 UTC

    Hi, try this one

    use Time::Piece; my $t = localtime; print $t->ymd;