Format string and date using perl

前端 未结 1 769
野性不改
野性不改 2021-01-28 03:04

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 ti

相关标签:
1条回答
  • 2021-01-28 03:17
    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)));
    
    0 讨论(0)
提交回复
热议问题