PHP | DateTime add() Function

The DateTime::add() function is an inbuilt function in PHP which is used to add an amount of time (days, months, years, hours, minutes and seconds) to the given DateTime object.

Syntax:

  • Object oriented style:
    DateTime DateTime::add( DateInterval $interval )
  • Procedural style:
    DateTime date_add( DateTime $object, DateInterval $interval )

Parameters: This function uses two parameters as mentioned above and described below:



  • $object: It specifies the DateTime object returned by date_create() function. This function returns a new DateTime object.
  • $interval: This parameter holds the DateInterval object.

Return Value: This function returns the new DateTime object after changing on success or False on failure.

Below programs illustrate the DateTime::add() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Initialising a DateTime
$datetime = new DateTime('2019-09-30');
  
// DateInterval object is taken as the 
// parameter of the add() function
// Here 1 day is added
$datetime->add(new DateInterval('P1D'));
  
// Getting the new date after addition
echo $datetime->format('Y-m-d') . "\n";
?>

chevron_right


Output:

2019-10-01

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Initialising a DateTime
$datetime = new DateTime('2019-09-30');
  
// DateInterval object is taken as the 
// parameter of the add() function
// Here 5 hours, 3 Minutes and 10 seconds is added
$datetime->add(new DateInterval('PT5H3M10S'));
  
// Getting the new date after addition
echo $datetime->format('Y-m-d H:i:s') . "\n";
?>

chevron_right


Output:

2019-09-30 05:03:10

Reference: https://www.php.net/manual/en/datetime.add.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.