david
david

Reputation: 122

Format string and date using perl

I would like to convert (using perl)

05\/26\/2013 06:09:47 to 26-05-2013 06:09:47

Also how can i change the above to GMT date and time?

Upvotes: 0

Views: 2986

Answers (1)

ikegami
ikegami

Reputation: 385655

use DateTime::Format::Strptime qw( );

my $src_format = DateTime::Format::Strptime->new(
   pattern   => '%m\\/%d\\/%Y %H:%M:%S',
   time_zone => 'local',   # or America/New_York
   on_error  => 'croak',
);

my $dst_format = DateTime::Format::Strptime->new(
   pattern   => '%d-%m-%Y %H:%M:%S',
);

my $dt = $src_format->parse_datetime('05\\/26\\/2013 06:09:47');
$dt->set_time_zone('GMT');
say $dst_format->format_datetime($dt);

If we're specifically dealing with local and UTC/GMT, then the following is lighter, though perhaps a bit more cryptic.

use POSIX       qw( strftime );
use Time::Local qw( timelocal );

my ($m,$d,$Y, $H,$M,$S) =
      '05\\/26\\/2013 06:09:47' =~
         m{^(\d+)\\/(\d+)\\/(\d+) (\d+):(\d+):(\d+)\z}
   or die;
say strftime('%d-%m-%Y %H:%M:%S', gmtime(timelocal($S,$M,$H, $d,$m-1,$Y-1900)));

Upvotes: 6

Related Questions