2
$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?

HDKT
  • 71
  • 1
  • 8

2 Answers2

3

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

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
1

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.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • For php < 5.5 use `$dateclone = clone $datenow` to clone it, and then modify cloned object. – Glavić Dec 02 '14 at 16:13
  • I also tried the clone method but DateTimeImmutable works better for me. The added one line of code is a deal breaker for me. – HDKT Dec 04 '14 at 15:19