HDKT
HDKT

Reputation: 81

Datetime Add/Subtract Miscalculation

$datenow    = new DateTime();
$dn = $datenow -> format("Y-m-d"); //2014-12-02
$yesterday  = $datenow -> sub(new DateInterval('P1D')) -> format("Y-m-d"); //2014-12-01
$yestertwo  = $datenow -> sub(new DateInterval('P2D')) -> format("Y-m-d"); //2014-11-29
$tomorrow   = $datenow -> add(new DateInterval('P1D')) -> format("Y-m-d"); //2014-11-30
$tomotwo    = $datenow -> add(new DateInterval('P2D')) -> format("Y-m-d"); //2014-12-02

I had to be missing something here. Date calculation seems to be off.

Update:

$datenow            = new DateTime();
$dn            = $datenow -> format("Y-m-d");
$yesterday     = $datenow -> sub(new DateInterval('P1D')) -> format("Y-m-d");
$yestertwo     = $datenow -> sub(new DateInterval('P1D')) -> format("Y-m-d");
$tomorrow      = $datenow -> add(new DateInterval('P3D')) -> format("Y-m-d");
$tomotwo       = $datenow -> add(new DateInterval('P1D')) -> format("Y-m-d");

This outputs the correct date now. However, it looks kind of messy and unreadable at first glance. Any solutions?

Upvotes: 2

Views: 229

Answers (2)

Evert
Evert

Reputation: 99687

As @ceejayoz mentioned, when you call add or sub on a DateTime object, you also modify it.

Since PHP 5.5 there's a new class: DateTimeImmutable. This class has methods like add and sub as well, but instead of modifying the original, it just returns a new object with the modification applied.

Replace $datenow = new DateTime(); with $datenow = new DateTimeImmutable(); and things should just start working.

Upvotes: 1

ceejayoz
ceejayoz

Reputation: 180065

You're modifying $datenow each time you sub/add, so you're essentially changing what "today" means.

Upvotes: 3

Related Questions