yyyymmddhhmmss to YYYY-MM-DD hh:mm:ss in perl?

前端 未结 3 1616
眼角桃花
眼角桃花 2021-01-06 08:48

What is the best way to convert yyyymmddhhmmss to YYYY-MM-DD hh:mm:ss and back in perl?

for example: 20130218165601 to 2013-02-18 16:56:01 and back? (can https://met

相关标签:
3条回答
  • 2021-01-06 09:21

    Quick solution with sprintf.

    my $date = sprintf "%s%s-%s-%s %s:%s:%s", $string =~ /(..)/g;
    

    And back:

    my $foo = join '', $date =~ /\d+/g;
    
    0 讨论(0)
  • 2021-01-06 09:21

    without regular expressions, you can just use substr to grab the characters you want:

    $year  = substr $d, 0, 4;
    $month = substr $d, 4, 2;
    ...
    $secs  = substr $d, 12, 2;
    
    0 讨论(0)
  • 2021-01-06 09:42

    A module is overkill for this.

    # Packed -> ISO
    (my $iso_date = $packed_date) =~
       s/^(....)(..)(..)(..)(..)(..)\z/$1-$2-$3 $4:$5:$6/s;
    
    # ISO -> Packed
    (my $packed_date = $iso_date) =~
       s/^(....)-(..)-(..) (..):(..):(..)\z/$1$2$3$4$5$6/s;
    

    Rose::DateTime cannot parse the "packed" format as intended, but you could use DateTime::Format::Strptime.

    use DateTime::Format::Strptime qw( );
    my $packed_format = DateTime::Format::Strptime->new(
       pattern  => '%Y%m%d%H%M%S',
       on_error => 'croak',
    );
    my $iso_format = DateTime::Format::Strptime->new(
       pattern  => '%Y-%m-%d %H:%M:%S',
       on_error => 'croak',
    );
    
    # Packed -> ISO
    my $iso_date = $iso_format->format_datetime(
       $packed_format->parse_datetime($packed_date)
    );
    
    # ISO -> Packed
    my $packed_date = $packed_format->format_datetime(
       $iso_format->parse_datetime($iso_date)
    );
    
    0 讨论(0)
提交回复
热议问题