I am trying to calculate the number of calendar days between two dates retrieved from a database. I thought converting dates to seconds would be a simple and correct solution.
#!/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";
At first I thought that this method gave me reliable results:
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$
Obviously, the number of calendar dates between dates must be an integer. Mmmm, what am I doing wrong? Why is conversion to seconds not reliable?
Since I'm new to Perl, I probably don't notice the obvious. Therefore any help is appreciated.
source share