How to Add or Subtract Date Interval In PHP

How to Add or Subtract Date Interval In PHP
Adding or subtracting interval to a DateTime instance is quite easy. Two methods we are going to described in this post. Both methods belong to DateTime object itself.

If you are using PHP 5.3+ version, than simply add and subtract method work for it.

See below example to Add 2 Day interval in date.

<?php

$date = new DateTime('2016-11-17');
$date->add(new DateInterval('P2D'));
echo $date->format('Y-m-d'); // 2016-11-19

?>

PID use for 1 day time interval, If you need to add 2 days, 1 month and 4 years than use P4Y1M2D.  To include time period interval format like that P1DT2H. It will add 1 day and 2 hours interval in date time.

To Subtract interval in DateTime check below example:

<?php
$date = new DateTime('2016-11-17');
$date->sub(new DateInterval('P1D'));
echo $date->format('Y-m-d'); // 2016-11-16
?>

For PHP 5.2 version simple modify method work for date interval. To add three days interval, just use ‘+3 day’. Check example code:

<?php
$date = new DateTime('2016-11-17');
$date->modify('+1 day');
echo $date->format('Y-m-d'); // 2016-11-18
?>

So use these simple method to Add or Subtract date time interval. In our previously blog post described Changing Date and Time Format. Share this post with others. Thanks

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *