Add or Subtract Date Intervals

suggest change

We can use the DateInterval class to add or subtract an interval from a DateTime object. add() and sub() both modify that object and return it.

See the example below, where we add an interval of 7 days and print a message:

$now = new DateTime('2016-08-01'); // an empty argument means the current date and time
$interval = new DateInterval('P7D'); // this object represents a 7-day interval
$lastDay = $now->add($interval); // modifies $now and returns the same object
$formattedLastDay = $lastDay->format('Y-m-d'); // format() returns a string
echo "Samara says: Seven Days. You'll be happy on $formattedLastDay.";

This will output:

Samara says: Seven Days. You'll be happy on 2016-08-08.

sub() works the same way. Start from the original date again, because $now is already seven days ahead:

$earlier = new DateTime('2016-08-01');
$earlier->sub($interval);
echo "Samara says: Seven Days. You were happy last on {$earlier->format('Y-m-d')}.";

This will output:

Samara says: Seven Days. You were happy last on 2016-07-25.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents