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: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";
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(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";
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
In reply to Re^3: What's "Better" DateTime or localtime?
by runrig
in thread What's "Better" DateTime or localtime?
by mmartin
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |