将日期格式从mm / dd / yyyy更改为yyyy-mm-dd

时间:2016-08-05 19:06:33

标签: perl

如何使用perl将02/01/1999更改为1999-02-01?我试过这个,但它正在返回DATE IS -00-00

sub changeDate{
    my $date = shift;
    my @adate=split (/\//, $date);
    my $ndate=$adate[2]."-".sprintf("%02d", $adate[1])."-".sprintf("%02d",$adate[0]);
    say "DATE IS $ndate";   
    return $ndate;
}

1 个答案:

答案 0 :(得分:0)

你拥有的是正确的。

$ perl -e'
    use feature qw( say );

    sub changeDate{
        my $date = shift;
        my @adate=split (/\//, $date);
        my $ndate=$adate[2]."-".sprintf("%02d", $adate[1])."-".sprintf("%02d",$adate[0]);
        return $ndate;
    }

    say changeDate("02/01/1999");
'
1999-01-02

您必须已将02/01/1999以外的内容传递给changeDate

请注意,changeDate可以缩减为以下内容:

sub changeDate { sprintf '%3$d-%1$02d-%2$02d', split /\//, shift }