One thing to watch out for is daylight savings conversions when adding/subtracting days. E.g., this may not work as expected, depending on what day and what time of day it is run (just as if using the builtin
localtime):
use Time::Piece qw(localtime);
use Time::Seconds qw(ONE_DAY);
my $t = localtime;
my $yesterday = $t - ONE_DAY();
my $tomorrow = $t + ONE_DAY();
print "Today: ", $t->ymd(),"\n";
print "Yesterday: ", $yesterday->ymd(),"\n";
print "Tomorrow: ", $tomorrow->ymd(),"\n";
I have found this sort of mistake in someone's code before (though the code did not use Time::Piece, just plain
localtime).
One way to be sure of adding or subtracting the correct number of days would be to truncate to the beginning of the day, then add an extra half day, or subtract a half-day less:
my $t = localtime->strptime(localtime->ymd(), '%Y-%m-%d');
my $yesterday = $t - ( 0.5 * ONE_DAY() );
my $tomorrow = $t + ( 1.5 * ONE_DAY() );
print "Today: ", $t->ymd(),"\n";
print "Yesterday: ", $yesterday->ymd(),"\n";
print "Tomorrow: ", $tomorrow->ymd(),"\n";
One advantage of
DateTime is that it does make it a little easier to get this correct. E.g. in my timezone:
my $t = localtime->strptime('2013-03-11', '%Y-%m-%d');
my $yesterday = $t - ONE_DAY();
my $tomorrow = $t + ONE_DAY();
print "Today: ", $t->ymd(),"\n";
print "Yesterday: ", $yesterday->ymd(),"\n";
print "Tomorrow: ", $tomorrow->ymd(),"\n";
#Prints:
Today: 2013-03-11
Yesterday: 2013-03-09
Tomorrow: 2013-03-12