The DateTime::sub() function is an inbuilt function in PHP which is used to subtract a number of days, months, years, hours, minutes and seconds from a created DateTime object.
Syntax:
- Object oriented style:
DateTime DateTime::sub( DateInterval interval )
- Procedural style:
DateTime date_sub( DateTime $object, DateInterval $interval )
Parameters: This function uses two parameters as mentioned above and described below:
- $object: This parameter holds the DateTime object created by date_create() function.
- $interval: This parameter holds the DateInterval object.
Return Values: This function returns the DateTime object after subtraction is done on success or False on failure.
Below programs illustrate the DateTime::sub() function in PHP:
Program 1: This program uses DateTime::sub() function to subtract 2 days from given date object.
<?php // PHP program to illustrate DateTime::sub() // function // Creating a new DateTime() object $datetime = new DateTime( '2019-10-03' ); // Initialising a interval of 2 days $interval = 'P2D' ; // Calling the sub() function $datetime ->sub( new DateInterval( $interval )); // Getting a new date time // format of 'Y-m-d' echo $datetime ->format( 'Y-m-d' ); ?> |
2019-10-01
Program 2: This program uses DateTime::sub() function to subtract the given interval from date object.
<?php // PHP program to illustrate DateTime::sub() // function // Creating a new DateTime() object $datetime = new DateTime( '2019-10-03' ); // Initialising an interval $interval = 'P2Y5M2DT0H30M40S' ; // Calling the sub() function $datetime ->sub( new DateInterval( $interval )); // Getting a new date time // format of 'Y-m-d H:i:s' echo $datetime ->format( 'Y-m-d H:i:s' ); ?> |
2017-04-30 23:29:20