in reply to Re: Subtracting and Comparing Two Dates
in thread Subtracting and Comparing Two Dates

Your solution doesn't always give the right answer.

Then Now Date::Calc BaldPenguin ---------- ------------------- ----------- ----------- 2005/08/01 2006/10/29 00:59:00 454 453.9993056 <- XXX 2005/08/01 2006/10/29 02:01:00 454 454.0840278 <- ok
use strict; use warnings; use POSIX qw( difftime mktime strftime ); use Time::Local qw( timegm timelocal ); use Date::Calc qw( Delta_Days ); use constant ONE_DAY_IN_SECS => 24 * 60 * 60; sub baseline { my ($then_date_str, $now) = @_; my ($y1, $m1, $d1) = $then_date_str =~ /^(\d{4})(\d{2})(\d{2})\z/; my ($y2, $m2, $d2) = (localtime($now))[5,4,3]; $y2 += 1900; $m2 += 1; return Delta_Days($y1, $m1, $d1, $y2, $m2, $d2); } sub bald_penguin { my ($then_date_str, $now) = @_; my @then = $then_date_str =~ /^(\d{4})(\d{2})(\d{2})/; my $then = mktime(0,0,0,$then[2],$then[1]-1,$then[0]-1900); return difftime($now, $then) / ONE_DAY_IN_SECS; } { print("Then Now Date::Calc BaldPenguin\n" +); print("---------- ------------------- ----------- -----------\n" +); for ( [ '20050801', timelocal(0, 59, 0, 29, 10-1, 2006) ], [ '20050801', timelocal(0, 1, 2, 29, 10-1, 2006) ], ) { printf("%s %s %3d %3d %11.7f\n", do { my ($y, $m, $d) = $_->[0] =~ /^(\d{4})(\d{2})(\d{2})\z/; + sprintf("%04d/%02d/%02d", $y, $m, $d) }, strftime('%Y/%m/%d %H:%M:%S', localtime($_->[1])), baseline(@$_), bald_penguin(@$_), ); } }