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
$datetime = new DateTime( '2019-10-03' );
$interval = 'P2D' ;
$datetime ->sub( new DateInterval( $interval ));
echo $datetime ->format( 'Y-m-d' );
?>
|
Program 2: This program uses DateTime::sub() function to subtract the given interval from date object.
<?php
$datetime = new DateTime( '2019-10-03' );
$interval = 'P2Y5M2DT0H30M40S' ;
$datetime ->sub( new DateInterval( $interval ));
echo $datetime ->format( 'Y-m-d H:i:s' );
?>
|
Output:
2017-04-30 23:29:20
Reference: https://www.php.net/manual/en/datetime.sub.php
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!