以下代码仅表示月份和日期的差异:
0:2:0:5:0:0:0
所以它有效,但我想知道$ ADDate可能会有很大变化的总天数。希望这很简单,我完全错过了如何做到这一点。
#!/usr/bin/perl
use Date::Manip 6.42;
my $ADDate = "20131211000820.0Z";
my $var;
my @val;
my $diff;
calc_period($ADDate = "20131211000820.0Z");
sub calc_period
{
$ADDate =~ s/^([\d][\d][\d][\d])([\d][\d])([\d][\d])/$1-$2-$3/gs;
$ADDate =~ s/.........$//gs;
$today = ParseDate("today");
$beginning = ParseDate($ADDate);
$end = ParseDate($today);
$delta = DateCalc($beginning,$end,\$err,1);
#$delta =~ s/([\d+][:][\d+]):.*$/$1/gs;
print "$delta\n";
print "$ADDate\n";
}
答案 0 :(得分:3)
我不熟悉Date :: Manip,但我认为另一种方法是使用Time::Piece来解析你的字符串并用taking the difference of two Time::Piece object returns a Time::Seconds object做你喜欢的任何事情。
以下示例将显示当前时间与硬编码时间的差异,并以天为单位显示。
#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;
use Time::Seconds;
my $d = "20131211000820.0Z";
my $t = Time::Piece->strptime($d, "%Y%m%d%H%M%S.0Z");
my $now = Time::Piece->localtime();
my $diff = Time::Seconds->new($now - $t);
print $diff->days, "\n";
答案 1 :(得分:1)
NigoroJr已经给你一个答案。但是,就像仅供参考,以下是我如何清理您最初提供的代码:
#!/usr/bin/perl
use Date::Manip 6.42;
use strict;
use warnings;
calc_period("20131211000820.0Z");
sub calc_period {
my $date = shift;
$date =~ s/^(\d{4})(\d{2})(\d{2}).*/$1-$2-$3/;
my $beginning = ParseDate($date);
my $end = ParseDate("today");
my $delta = DateCalc($beginning, $end, \my $err, 1);
#$delta =~ s/([\d+][:][\d+]):.*$/$1/gs;
print "$delta\n";
print "$date\n";
}
最大的区别在于正确使用函数和作用域变量,以及简化正则表达式。
我无法找到一种简洁的方法来让Date :: Manip在几天内输出严格的delta,所以另一个模块就是这样。