perl how to convert a string to Datetime?

前端 未结 3 993
天涯浪人
天涯浪人 2021-02-05 10:06

I tried to convert a string to date in perl, but get error.

use strict; 
use warnings;  
use DateTime;  
use Date::Manip;

my $date = ParseDate(\"20111121\");
p         


        
相关标签:
3条回答
  • 2021-02-05 10:38

    From the module documentation: This module does not parse dates

    You need to add code such as suggested in I printed a date with strftime, how do I parse it again? to convert from a string to a date time object.

    0 讨论(0)
  • 2021-02-05 10:39

    DateTime itself has no parsing facility, but there are many parsers that gererate DateTime objects. Most of the time, you'll probably want DateTime::Format::Strptime.

    use DateTime::Format::Strptime qw( );
    my $format = DateTime::Format::Strptime->new(
       pattern   => '%Y%m%d',
       time_zone => 'local',
       on_error  => 'croak',
    );
    my $dt = $format->parse_datetime('20111121');
    

    Or you could do it yourself.

    use DateTime qw( );
    my ($y,$m,$d) = '20111121' =~ /^([0-9]{4})([0-9]{2})([0-9]{2})\z/
       or die;
    my $dt = DateTime->new(
       year      => $y,
       month     => $m,
       day       => $d,
       time_zone => 'local',
    );
    
    0 讨论(0)
  • 2021-02-05 10:41

    DateTime doesn't parse dates. I'd go for the Time::Piece core module that gives you strptime():

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use Time::Piece;
    my $t = Time::Piece->strptime("20111121", "%Y%m%d");
    print $t->strftime("%w\n");
    
    0 讨论(0)
提交回复
热议问题