Steve W Steve W - 6 months ago 8
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

YYYY-MM-DD HH:MM:SS
format.

I have it in a variable called
$field0
along with another nine variables
$field1
-
$field9
.

Using Perl I want to change the format of the string to
DD-MM-YYYY HH:MM:SS
and put it back in
$field0


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

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

Answer

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;

output

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