Search code examples
perlstrftime

print strfitime in perl


Here is my current code:

print "<td class=resa>@res[$i]->{'signupdate'}</td></tr>\n";

I want to modify the variable @res[$i]->{'signupdate'} to be a formatted date. The data is 201710130915 for that variable.

I've tried:

use POSIX qw(strftime);
my $date=strftime('%Y-%m-%d',@res[$i]->{'signupdate'});
print "<td class=resa>$date</td></tr>\n";

Any suggestions?


Solution

  • The data you have looks like a string representation of a date.

    YYYYMMDDhhmm
    201710130915
    

    It can therefore easily be deconstructed with a pattern match and put back together in a different format.

    my $time = "201710130915";
    
    my ($year, $month, $day) = $time =~ m/^(....)(..)(..)/;
    my $date = sprintf '%d-%02d-%02d', $year, $month, $day;
    
    print $date;
    

    This will print

    2017-10-13