Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Date displaying the 0's

by Anonymous Monk
on Apr 09, 2006 at 18:58 UTC ( #542167=perlquestion: print w/ replies, xml ) Need Help??
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!

Comment on Date displaying the 0's
Download Code
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 (Monsignor) 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;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://542167]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (14)
As of 2014-08-27 14:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (241 votes), past polls