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

knorv picture knorv · Oct 17, 2010 · Viewed 10.6k times · Source

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?

Answer

eumiro picture eumiro · Oct 17, 2010

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);