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);
Run Code Online (Sandbox Code Playgroud)
它不起作用; 问题是什么?
错误消息是:
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
Run Code Online (Sandbox Code Playgroud)
Eth*_*her 19
您需要首先使用自定义格式或可用的许多DateTime :: Format ::*库之一将日期字符串转换为DateTime对象.您正在使用数据库中常用的格式,因此我选择了MySQL格式化程序(然后为最终结果定义了自定义持续时间格式化程序,从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
Run Code Online (Sandbox Code Playgroud)
$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
Run Code Online (Sandbox Code Playgroud)