• PHP Video Tutorials

PHP date_add() Function



Definition and Usage

The date_add() function is an alias of DateTime::add(). It accepts a DateTime object as parameters and a DateInterval object, adds the specified interval to the given DateTime.

Syntax

date_add($object, $interval)

Parameters

Sr.No Parameter & Description
1

object(Optional)

This is a DateTime object specifying/representing the date to which you need to add the time interval.

2

interval (Optional)

This is a DateInterval object specifying the interval to be added.

Return Values

PHP date_add() function returns a DateTime object with added interval. In case of failure, this function returns the boolean value false.

PHP Version

This function was first introduced in PHP Version 5.3.0 and, works with all the later versions.

Example

Following example demonstrates the usage of the date_add() function −

<?php
   //Creating a DateTime object
   $date = date_create("25-09-1989");
   //Adding interval to the date
   $res = date_add($date, new DateInterval('PT10H30S'));   
   //formatting the date to print it
   $format = date_format( $res, "d-m-Y H:i:s");
   print($format);
?>

This will produce following result −

25-09-1989 10:00:30

Example

You can create an interval using the date_interval_create_from_date_string() function. Following example creates an interval using this function, adds it to a date −

<?php
   $date = date_create("25-09-1989");
   $interval = date_interval_create_from_date_string('1025 days');
   $res = date_add($date, $interval);   
   $format = date_format( $res, "d-m-Y H:i:s");
   print($format);   
?>

This will produce following result −

16-07-1992 00:00:00

Example

Now, let us try to add interval with years, months and days −

<?php
   //Creating a DateTime object
   $date = date_create("25-09-1989");
   //Adding interval to the date
   $res = date_add($date, new DateInterval('P29Y2M5D'));   
   //formatting the date to print it
   $format = date_format( $res, "d-m-Y");
   print($format);
?>

This will produce following result −

30-11-2018

Example

<?php
   $date = date_create('1995-05-07');
   $interval = date_interval_create_from_date_string('150 days');
   $date->add($interval);
   print($date -> format('d-m-Y'));
?>

This produces the following result −

04-10-1995
php_function_reference.htm
Advertisements