herdofturtles21 herdofturtles21 - 4 months ago 6
Perl Question

Change date format and add the day

I need help with changing the format of a date and adding the day. Right now the date is MMYY (0919) and I need it to be YYYY-MM-DD(2019-09-01) with the day always being 01. Any help would be greatly appreciated!

Answer

If the date is always in the 21st century then you can use a simple regex substitution, like this

use strict;
use warnings 'all';
use feature 'say';

say convert_date('0919');

sub convert_date {
    (my $yyyymmdd = shift) =~ s/(\d\d)(\d\d)/20$2-$1-01/;
    $yyyymmdd;
}

output

2019-09-01

This may be abbreviated if you are running Perl v 5.14 or later, like this

sub convert_date {
    shift =~ s/(\d\d)(\d\d)/20$2-$1-01/r;
}
Comments