use DateTime ;
my $date = "2010-08-02 09:10:08";
my $dt = DateTime->now( time_zone => 'local' )->set_time_zone('floating');
print $dt->subtract_datetime($date);
它不起作用;问题是什么?
错误消息是:
Can't call method "time_zone" without a package or object reference at
/opt/perl/perl5.12/lib/site_perl/5.12.0/x86_64-linux/DateTime.pm line 1338
答案 0 :(得分:19)
您需要先使用a将日期字符串转换为DateTime对象 自定义格式或可用的许多DateTime :: Format :: *库之一。 您使用的是数据库中常用的格式,因此我选择了MySQL formatter(然后为最终结果定义自定义持续时间格式化程序, 从中的示例复制而来 DateTime::Format::Duration):
use DateTime;
use DateTime::Format::MySQL;
use DateTime::Format::Duration;
my $date = "2010-08-02 09:10:08";
my $dt1 = DateTime->now(time_zone => 'floating', formatter => 'DateTime::Format::MySQL');
my $dt2 = DateTime::Format::MySQL->parse_datetime($date);
my $duration = $dt1 - $dt2;
my $format = DateTime::Format::Duration->new(
pattern => '%Y years, %m months, %e days, %H hours, %M minutes, %S seconds'
);
print $format->format_duration($duration);
# prints:
# 0 years, 00 months, 0 days, 00 hours, 421 minutes, 03 seconds
答案 1 :(得分:6)
$date
必须是DateTime
对象,而不是简单的字符串。看到
DateTime。并且,您不能简单地打印返回值
subtract_datetime
因为它返回一个引用。你必须使用
方法,例如hours
,用于提取有用的信息。
use strict;
use warnings;
use DateTime;
my $dt2 = DateTime->new(
year => 2010,
month => 8,
day => 2,
hour => 9,
minute => 10,
second => 8,
time_zone => 'local',
);
my $dt1 = DateTime->now( time_zone => 'local' )->set_time_zone('floating');
my $dur = $dt1->subtract_datetime($dt2);
print 'hours = ', $dur->hours(), "\n";
__END__
hours = 2
答案 2 :(得分:4)
嗯,乍一看,我想如果你减去两个日期时间对象,$dt->subtract_datetime(...)
将会起作用。
即:您的$date
应该是日期时间