如何计算 Perl 中的 DateTime 差异? [英] How do I calculate a DateTime difference in Perl?

查看:56
本文介绍了如何计算 Perl 中的 DateTime 差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

它不起作用;问题是什么?

It's not working; what is the problem?

错误信息是:

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

推荐答案

您需要先将日期字符串转换为 DateTime 对象,使用一个自定义格式或许多可用的 DateTime::Format::* 库之一.您使用的是数据库中常用的格式,所以我选择了 MySQL格式化程序(然后为最终结果定义自定义持续时间格式化程序,从示例中复制DateTime::Format::Duration):

You need to convert date strings into DateTime objects first, using a customized format or one of the many DateTime::Format::* libraries available. You're using a format commonly used in databases, so I've selected the MySQL formatter (and then defined a custom duration formatter for the end result, copied from the examples in 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

这篇关于如何计算 Perl 中的 DateTime 差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆