Search code examples
perldatetimelocaltime

Quickly getting to local time YYYY-mm-dd HH:MM:SS in Perl?


i want to get local time and formatted as YYYY-mm-dd HH:MM:SS (say 2009-11-29 14:28:29)., How can i get date in this format YYYY-mm-dd HH:MM:SS ?

i have try

my $format = "%4u-%02u-%02u %02u:%02u:%02u";
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
printf "$format\n", $year+1900, $mon+1, $mday, $hour, $min, $sec;

the print output is that i want ,but how to designed the output to a variable ??


Solution

  • Use sprintf instead of printf.

    my ($sec, $min, $hour, $mday, $mon, $year) = localtime;
    my $formatted = sprintf "%4u-%02u-%02u %02u:%02u:%02u",
       $year+1900, $mon+1, $mday, $hour, $min, $sec;
    

    But it's much simpler to use strftime.

    use POSIX qw( strftime );
    my $formatted = strftime("%Y-%m-%d %H:%M:%S", localtime);