我尝试在perl中将字符串转换为日期,但是会出错。
use strict;
use warnings;
use DateTime;
use Date::Manip;
my $date = ParseDate("20111121");
print "today is ".$date->day_of_week."\n";
错误
Can't call method "day_of_week" without a package or object reference
看起来包导入有问题......
由于
答案 0 :(得分:22)
DateTime不会解析日期。我会选择Time::Piece核心模块给你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");
答案 1 :(得分:22)
DateTime本身没有解析工具,但有许多parsers可以对DateTime对象进行生成。大多数情况下,您可能需要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');
或者你可以自己做。
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',
);
答案 2 :(得分:0)
从模块文档:This module does not parse dates
您需要添加I printed a date with strftime, how do I parse it again?中建议的代码,以便将字符串转换为日期时间对象。