Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
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
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 (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 surveying the Monastery: (12)
As of 2015-07-28 10:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (254 votes), past polls