Perl:通过转换为秒来计算天数

时间:2016-06-16 15:27:29

标签: perl

我正在尝试计算从数据库中提取的两个日期之间的日历天数。我认为将日期转换为秒将是一个简单而正确的解决方案。

#!/usr/bin/perl
use warnings;
use strict;
use POSIX qw(strftime);
use Date::Parse;

my $minDate = "2016-03-27";
my $maxDate = "2016-06-15";

print "Format as extracted from db: mindate: $minDate and maxdate: $maxDate\n"; 

my ($dbYear,$dbMonth,$dbDay) = split ('-', $minDate);
my $datum = "$dbYear$dbMonth$dbDay";
my $minDateSec = str2time($datum);

($dbYear,$dbMonth,$dbDay) = split ('-', $maxDate);
$datum = "$dbYear$dbMonth$dbDay";
my $maxDateSec = str2time($datum);

my $numCalDaysSec = ($maxDateSec-$minDateSec)/86400;

print "Min date in Seconds: $minDateSec\n";
print "Max date in Seconds: $maxDateSec\n";
print "Num days: $numCalDaysSec\n";

最初,我认为这种方法为我提供了可靠的结果:

bash-3.2$ ./testNumDays.pl
As extracted from db: mindate: 2016-06-14 and maxdate: 2016-06-15
Min date in Seconds: 1465855200
Max date in Seconds: 1465941600
Num days: 1
bash-3.2$ ./testNumDays.pl
As extracted from db: mindate: 2016-05-31 and maxdate: 2016-06-15
Min date in Seconds: 1464645600
Max date in Seconds: 1465941600
Num days: 15
bash-3.2$ ./testNumDays.pl
As extracted from db: mindate: 2016-03-28 and maxdate: 2016-06-15
Min date in Seconds: 1459116000
Max date in Seconds: 1465941600
Num days: 79
bash-3.2$ ./testNumDays.pl
As extracted from db: mindate: 2016-03-27 and maxdate: 2016-06-15
Min date in Seconds: 1459033200
Max date in Seconds: 1465941600
Num days: 79.9583333333333
bash-3.2$

显然,日期之间的日历日期数应为整数。嗯,我做错了什么?为什么转换为秒不可靠?

由于我是一名Perl新手,我可能会忽略这一点。因此,非常欢迎任何帮助。

3 个答案:

答案 0 :(得分:7)

一种方法是使用Time::Piece核心模块:

use warnings;
use strict;
use Time::Piece qw();

my $t1 = Time::Piece->strptime('2016-03-27', '%Y-%m-%d');
my $t2 = Time::Piece->strptime('2016-06-15', '%Y-%m-%d');
my $seconds = $t2 - $t1;
print $seconds->days(), "\n";

__END__

80

答案 1 :(得分:5)

另一种选择是DateTime。它不在Core中,但它通常非常方便。因为它不解析日期,所以我们很快就建立了自己的解析函数。

use strict;
use warnings;
use DateTime;
my $minDate = "2016-03-27";
my $maxDate = "2016-06-15";

sub parse {
    my $date = shift;

    my ( $y, $m, $d ) = split /-/, $date;

    return DateTime->new( year => $y, month => $m, day => $d );
}

my $days = parse($minDate)->delta_days(parse($maxDate))->in_units('days');
print $days;

__END__

80

答案 2 :(得分:3)

您做出的无效假设是每天的时长为86,400秒。

请转到http://www.timeanddate.com/time/dst/2016.html并查看2016年3月27日夏令时(又名夏令时)开始的所有地方。那天不是86,400秒。