views:

76

answers:

4

What is the recommended way of doing date arithmetics in Perl?

Say for example that I want to know the date three days ago from today (where today = 2010-10-17 and today - 3 days = 2010-10-13). How would you do that in Perl?

+6  A: 

See DateTime on CPAN (or here).

zoul
+8  A: 

You can use DateTime and DateTime::Duration

http://search.cpan.org/dist/DateTime/lib/DateTime/Duration.pm

Or work with unix timestamps:

my $now = time();
my $threeDaysAgo = $now - 3 * 86400;
my ($day, $mon, $year) = (localtime($threeDaysAgo))[3, 4, 5];
printf("Three days ago was %04d-%02d-%02d", $year+1900, $mon+1, $day);
eumiro
you don't even need to bother with DateTime::Duration itself for a lot of date manipulation, e.g. `$three_days_ago = DateTime->now()->subtract( days => 3 )`
plusplus
The only thing to take care, using DateTime, is to minimize the number of DateTime objects you instantiate (could be pretty time consuming to allocate and destroy). Reuse as often as possible.
OMG_peanuts
+5  A: 

There are many, many different date and time manipulation modules.

These include:

All of these are well thought of. There are many others in addition. A lot depends on the sort of arithmetic you want to do. DateTime is perhaps the most rigorous, but Date::Calc and Date::Manip may be easier to handle for the work you need.

Jonathan Leffler
A: 

This is by far the module with the most functionality that I've come across: Date::Manip

ennuikiller