Steve W Steve W - 4 months ago 5x
Perl Question

Perl: Converting a date held in a string to a different format

I have a date that I have extracted from a log file in


I have it in a variable called
along with another nine variables

Using Perl I want to change the format of the string to
and put it back in

Surely there must be a really easy way to do this?

Can anyone assist please or point me somewhere that has am example?


There are two obvious approaches. The first is to use the core Time::Piece module to parse the date-time string and reformat it, and the second is to use a regex substitution to match the three date fields and reverse them

Here are both techniques used in a single program

use strict;
use warnings qw/ all FATAL /;
use feature 'say';

use Time::Piece;

my $time0 = my $time1 = '2016-05-28 12:53:19';

$time0 = Time::Piece->strptime($time0, '%Y-%m-%d %H:%M:%S')->strftime('%d-%m-%Y %H:%M:%S');
say $time0;

$time1 =~ s/^(\d\d\d\d)-(\d\d)-(\d\d)/$3-$2-$1/;
say $time1;


28-05-2016 12:53:19
28-05-2016 12:53:19