herdofturtles21 herdofturtles21 - 4 months ago 10
Perl Question

Change format of date from mm/dd/yyyy to yyyy-mm-dd

How would I change 02/01/1999 to 1999-02-01 using perl? Ive tried this but it is returning 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;
}

Answer

What you have is correct.

$ 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

You must have passed something other than 02/01/1999 to changeDate.

Note that changeDate can be reduce to the following:

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