Search code examples
perltimeposixstrftimelocaltime

Perl convert time in localtime format to YYYYMMDD


I have a string containing a date with this format

my $time = 'Fri Jan  8 14:24:27 2016';

And i want to convert it to YYYYMMDD. I tried a couple of options such as :

use POSIX qw(strftime);
print strftime("%Y%m%d", $time);

But it won't work. Tried localtime($time) as well as many others but it won't work.

I guess i need to convert it to an intermediary format ?

Note : i need to use strftime/POSIX as i can't call other modules for many reasons. (no Date::Time etc.)

thanks in advance,


Solution

  • Use Time::Piece, part of the Perl core since 2007:

    use Time::Piece;
    
    my $time = 'Fri Jan  8 14:24:27 2016';
    say Time::Piece->strptime($time, '%a %b %d %H:%M:%S %Y')->ymd("");