PHP | date_sub() Function

The date_sub() is an inbuilt function in PHP which is used to subtract some days, months, years, hours, minutes, and seconds from given date. The function returns a DateTime object on success and returns FALSE on failure.

Syntax:

date_sub($object, $interval)

Parameters: The date_sub() function accepts two parameters as described below:



  • $object: It is a mandatory parameter which specifies the DateTime object returned by date_create()
  • $interval: It is a mandatory parameter which specifies the DateInterval object which we want to subtract.

Return Value: It returns a DateTime object after subtracting interval.

Below programs ilustrate the date_sub() function:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to illustrate date_sub() function
  
// Subtract 5 years from the 25th of June, 2018
$date = date_create('2018-06-25');
date_sub($date, date_interval_create_from_date_string('5 years'));
  
echo date_format($date, 'Y-m-d') . "\n";
  
  
// Subtract 5 month from the 25th of June, 2018
$date = date_create('2018-06-25');
date_sub($date, date_interval_create_from_date_string('5 month'));
  
echo date_format($date, 'Y-m-d'). "\n";
  
// // Subtract 5 days from the 25th of June, 2018
$date = date_create('2018-06-25');
date_sub($date, date_interval_create_from_date_string('5 days'));
  
echo date_format($date, 'Y-m-d');
  
?>

chevron_right


Output:

2013-06-25
2013-01-25
2013-01-20

Program 2: When invalid date is passed the date_sub function gives warnings:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to illustrate date_sub function
  
// date_sub function gives warning when
// we passing invalid date
$date = date_create('2018-25-25');
  
date_sub($date, date_interval_create_from_date_string('5 years'));
  
echo date_format($date, 'Y-m-d') . "\n";
?>

chevron_right


Output:

PHP Warning: date_sub() expects parameter 1 to be DateTime, boolean given in/home
/2662efc623a406b7cb06a7320e7abf50.php on line 8 PHP Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean
given in/home/2662efc623a406b7cb06a7320e7abf50.php on line 9

Reference: http://php.net/manual/en/function.date-sub.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.