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

editclose

play_arrow

linkbrightness_4code

<?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'));

echodate_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'));

echodate_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'));

echodate_format($date, 'Y-m-d');

?>

chevron_right

filter_none

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

editclose

play_arrow

linkbrightness_4code

<?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'));

echodate_format($date, 'Y-m-d') . "\n";

?>

chevron_right

filter_none

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, booleangiven in/home/2662efc623a406b7cb06a7320e7abf50.php on line 9

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.