使用perl格式化字符串和日期

时间:2013-06-06 05:18:20

标签: perl

我想转换(使用perl)

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

另外,如何将上述内容更改为GMT日期和时间?

1 个答案:

答案 0 :(得分:6)

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);

如果我们专门处理本地和UTC / GMT,那么下面的内容会更轻,但可能会更加神秘。

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)));