3.5. Difference of Two DatesProblemYou need to find the number of days between two dates or times. Solution
If your dates are in Epoch seconds, and fall in the range $seconds = $recent - $earlier;
If you have distinct DMYMHS values, or are worried about the range limitations of Epoch seconds, use the
Date::Calc module from CPAN. It can calculate the difference between dates: use Date::Calc qw(Delta_Days); $days = Delta_Days( $year1, $month1, $day1, $year2, $month2, $day2); It also calculates the difference between dates and times: use Date::Calc qw(Delta_DHMS); ($days, $hours, $minutes, $seconds) = Delta_DHMS( $year1, $month1, $day1, $hour1, $minute1, $seconds1, # earlier $year2, $month2, $day2, $hour2, $minute2, $seconds2); # later DiscussionOne problem with Epoch seconds is how to convert the large integers back to forms that people can read. The following example shows one way of converting an Epoch seconds value back to its component numbers of weeks, days, hours, minutes, and seconds: $bree = 361535725; # 16 Jun 1981, 4:35:25 $nat = 96201950; # 18 Jan 1973, 3:45:50 $difference = $bree - $nat; print "There were $difference seconds between Nat and Bree\n";
Date::Calc's functions can ease these calculations.
use Date::Calc qw(Delta_Days);
@bree = (1981, 6, 16); # 16 Jun 1981
@nat = (1973, 1, 18); # 18 Jan 1973
$difference = Delta_Days(@nat, @bree);
print "There were $difference days between Nat and Bree\n";
use Date::Calc qw(Delta_DHMS);
@bree = (1981, 6, 16, 4, 35, 25); # 16 Jun 1981, 4:35:25
@nat = (1973, 1, 18, 3, 45, 50); # 18 Jan 1973, 3:45:50
@diff = Delta_DHMS(@nat, @bree);
print "Bree came $diff[0] days, $diff[1]:$diff[2]:$diff[3] after Nat\n";
Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|