PHP date_sub() Function
Last Updated :
29 Jan, 2024
The date_sub() function is an inbuilt function in PHP that is used to subtract days, months, years, hours, minutes, and seconds from given date. This function returns a DateTime object on success and FALSE on failure.
Syntax:
date_sub($object, $interval)
Parameters: The date_sub() function accepts two parameters as described below:
- $object: It is a required parameter that specifies the DateTime object returned by date_create() function.
- $interval: It is a required parameter that specifies the DateInterval object that we want to subtract.
Return Value: It returns a DateTime object after subtracting the interval. Below programs illustrate the date_sub() function:
Program 1:
php
<?php
$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" ;
$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" ;
$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
2018-01-25
2018-06-20
Program 2: When invalid date is passed the date_sub function return a warning message.
php
<?php
$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:
Warning: date_sub() expects parameter 1 to be DateTime, bool given in /home/guest/sandbox/Solution.php on line 8
Warning: date_format() expects parameter 1 to be DateTimeInterface, bool given in /ho...
Reference: http://php.net/manual/en/function.date-sub.php
Share your thoughts in the comments
Please Login to comment...