PHP | DateTime sub() Function
Last Updated :
10 Oct, 2019
Improve
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:
php
php
- Object oriented style:
DateTime DateTime::sub( DateInterval interval )
- Procedural style:
DateTime date_sub( DateTime $object, DateInterval $interval )
- $object: This parameter holds the DateTime object created by date_create() function.
- $interval: This parameter holds the DateInterval 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');
?>
<?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');
?>
Output:
Program 2: This program uses DateTime::sub() function to subtract the given interval from date object.
2019-10-01
<?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');
?>
<?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');
?>
Output:
Reference: https://www.php.net/manual/en/datetime.sub.php
2017-04-30 23:29:20