如何计算Perl中两个日期之间的天数? [英] How can I calculate the number of days between two dates in Perl?

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

问题描述

Heylo

我想计算(仅使用默认的Perl安装)两个日期之间的天数。这两个日期的格式就像04年5月04日。 (DD-MMM-YY)

I want to calculate (using the default Perl installation only) the number of days between two dates. The format of both the dates are like so 04-MAY-09. (DD-MMM-YY)

我找不到任何讨论该日期格式的教程。我应该为这种格式建立一个自定义日期检查器吗?进一步阅读CPAN上的 Date :: Calc ,这种格式似乎不太受支持。

I couldn't find any tutorials that discussed that date format. Should I be building a custom date checker for this format? Further reading of the Date::Calc on CPAN it looks unlikely that this format is supported.

谢谢。

推荐答案

如果你关心准确性,记住,并不是所有的日子都有86400秒。基于这种假设的任何解决方案在某些情况下都是不正确的。

If you care about accuracy, keep in mind that not all days have 86400 seconds. Any solution based on that assumption will not be correct for some cases.

这是一个代码片段,我可以用几种不同的方法来计算和显示日期/时间差异,一个href =http://search.cpan.org/dist/DateTime/ =noreferrer> DateTime 库。打印的最后一个答案是你想要的答案。

Here's a snippet I keep around to calculate and display date/time differences a few different ways using the DateTime library. The last answer printed is the one you want, I think.

#!/usr/bin/perl -w

use strict;

use DateTime;
use DateTime::Format::Duration;

# XXX: Create your two dates here
my $d1 = DateTime->new(...);
my $d2 = DateTime->new(...);

my $dur = ($d1 > $d2 ? ($d1->subtract_datetime_absolute($d2)) : 
                       ($d2->subtract_datetime_absolute($d1)));

my $f = DateTime::Format::Duration->new(pattern => 
  '%Y years, %m months, %e days, %H hours, %M minutes, %S seconds');

print $f->format_duration($dur), "\n";

$dur = $d1->delta_md($d2);

my $dy = int($dur->delta_months / 12);
my $dm = $dur->delta_months % 12;
print "$dy years $dm months ", $dur->delta_days, " days\n";
print $dur->delta_months, " months ", $dur->delta_days, " days\n";
print $d1->delta_days($d2)->delta_days, " days\n";

这篇关于如何计算Perl中两个日期之间的天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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