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,$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新手,我可能会忽略这一点.因此,非常欢迎任何帮助.

解决方法

一种方法是使用 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

相关文章

忍不住在 PerlChina 邮件列表中盘点了一下 Perl 里的 Web 应用框架(巧的是 PerlBuzz 最近也有一篇相关...
bless有两个参数:对象的引用、类的名称。 类的名称是一个字符串,代表了类的类型信息,这是理解bless的...
gb2312转Utf的方法: use Encode; my $str = "中文"; $str_cnsoftware = encode("utf-8...
  perl 计算硬盘利用率, 以%来查看硬盘资源是否存在IO消耗cpu资源情况; 部份代码参考了iostat源码;...
1 简单变量 Perl 的 Hello World 是怎么写的呢?请看下面的程序: #!/usr/bin/perl print "Hello W...
本文介绍Perl的Perl的简单语法,包括基本输入输出、分支循环控制结构、函数、常用系统调用和文件操作,...