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:
<?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'); ?> |
Output:
2013-06-25 2013-01-25 2013-01-20
Program 2: When invalid date is passed the date_sub function gives warnings:
<?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"; ?> |
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
Recommended Posts:
- How to call a function that return another function in JavaScript ?
- How to get the function name from within that function using JavaScript ?
- How to get the function name inside a function in PHP ?
- PHP | Ds\Map first() Function
- PHP Ds\Map sum() Function
- p5.js | hex() function
- p5.js | nf() Function
- p5.js | abs() function
- p5.js | str() function
- p5.js | nfs() Function
- PHP | dir() Function
- p5.js | sq() function
- D3.js | d3.map.get() Function
- p5.js | nfp() Function
- D3.js | d3.map.has() Function
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.



