Calendar Calisthenics
December 13, 1999
Much earlier in this article we saw that, using epoch time, it
is relatively easy to add or subtract periods
of time. Although true, it is still sometimes easier to
express periods of times in ways other than seconds, and
Date::Manip provides a handy way to calculate time using more
human friendly terms, namely the &DateCalc
subroutine.
Suppose you wish to simply add 12 hours to the current time.
$time=&DateCalc("today","+12 hours");
print scalar localtime(&UnixDate($time,"%s"));
Or subtract 12 hours from the current time.
$time=&DateCalc("today","-12 hours");
print scalar localtime(&UnixDate($time,"%s"));
In fact, you can even write "-12 hours" as "12
hours ago" and Date::Manip would still understand
although, it must be said, that's just a little too clever
for its own good!
Obviously you can add or subtract compound times as well:
$time=&DateCalc("today","+3 days 12 hours 30 minutes");
print scalar localtime(&UnixDate($time,"%s"));
Conveniently, the Date::Manip module is also aware of certain
human time conventions, such as the notion of
"business days", or days which fall within Monday
through Friday. Thus, you can for instance, as UPS
and FedEx like to do, calculate "3 business days"
from tomorrow:
$time=&DateCalc("tomorrow","+3 business days");
print scalar localtime(&UnixDate($time,"%s"));
Another useful trick is to determine how much time has
elapsed between two times. You could certainly do this
in epoch time, but you'd be left with a differential in
seconds, forcing you to convert this into some suitable
breakdown of minutes, hours, days, or months. Date::Manip
lends a hand. For instance, how much time has passed
between Halloween and Christmas of 1999?
$timeDelta=&DateCalc(&ParseDate("31 October 1999"),
&ParseDate("December 25, 1999"),\$err,1);
print $timeDelta;
Yields, in the form YY:MM:WK:DD:HH:MM:SS
+0:1:3:4:0:0:0
What have we learned? That 1 month, 3 weeks, and 4 days
elapsed between Halloween and Christmas. Bet you didn't
know that before.
Date::Manip Gymnastics
The Perl You Need to Know
Conclusions
|