PHP | DateTime sub() Function

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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');
?>

chevron_right


Output:

2019-10-01

Program 2: This program uses DateTime::sub() function to subtract the given interval from date object.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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');
  
?>

chevron_right


Output:

2017-04-30 23:29:20

Reference: https://www.php.net/manual/en/datetime.sub.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.