Add or Subtract Date Intervals

suggest change

We can use the class DateInterval to add or subtract some interval in a DateTime object.

See the example below, where we are adding an interval of 7 days and printing a message on the screen:

$now = new DateTime();// empty argument returns the current date
$interval = new DateInterval('P7D');//this objet represents a 7 days interval
$lastDay = $now->add($interval); //this will return a DateTime object
$formatedLastDay = $lastDay->format('Y-m-d');//this method format the DateTime object and returns a String
echo "Samara says: Seven Days. You'll be happy on $formatedLastDay.";

This will output (running on Aug 1st, 2016):

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

We can use the sub method in a similar way to subtract dates

$now->sub($interval);
echo "Samara says: Seven Days. You were happy last on $formatedLastDay.";

This will output (running on Aug 1st, 2016):

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