PHP Date_sub () function

PHP

Syntax:
date_sub ($object, $interval) 
Parameters:The date_sub() function takes two parameters as described below:
  • $object:this is a required parameter that specifies the DateTime object returned by by date_create()
  • $interval:this is a required parameter that specifies the DateInterval object we are want to subtract.
Returned value:returns a DateTime object after the subtraction interval.The programs below illustrate the date_sub() function:
Program 1:
// PHP program to illustrate the date_sub() function 
// Subtract 5 years from June 25, 2018 $date = date_create ( '2018-06-25' ); date_sub ( $date , date_interval_create_from_date_string ( '5 years' )); echo date_format ( $date , ' Ymd' ). "" ;  
// Subtract 5 months from June 25, 2018 $date = date_create ( '2018-06-25' ); date_sub ( $date , date_interval_create_from_date_string ( '5 month' )); echo date_format ( $date , ' Ymd' ). "" ;  
// // Subtract 5 days from June 25, 2018 $date = date_create ( '2018-06 -25' ); date_sub ( $date , date_interval_create_from_date_string ( '5 days' )); echo date_format ( $date , ' Ymd' );  
?>
Exit :
2013-06-25 2013-01-25 2013-01-20 
Program 2:When an invalid date is passed, the date_sub function will issue warnings:
// PHP program for illustrating the date_sub function  
// the date_sub function issues a warning when
// we are missing the wrong date $date = date_create ( '2018-25-25' ); date_sub ( $date , date_interval_create_from_date_string ( ' 5 years' )) ; echo date_format ( $date , ' Ymd' ). "" ; ?>
Exit :
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
Link: http://php.net/manual/en/function.date-sub.php