Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl how to convert a string to Datetime?

Tags:

datetime

perl

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");
print "today is ".$date->day_of_week."\n"; 

error

Can't call method "day_of_week" without a package or object reference 

Looks like the package import has problem ...

Thanks

like image 464
user595234 Avatar asked Nov 21 '11 20:11

user595234


1 Answers

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',
);
like image 132
ikegami Avatar answered Sep 28 '22 08:09

ikegami