PHP date add function


 

PHP date add function

In this tutorial we will discuss PHP date add function. We will also show you good examples of PHP date add function.

In this tutorial we will discuss PHP date add function. We will also show you good examples of PHP date add function.

PHP Add Date function - date_add or DateTime::add function

The date_add function or DateTime::add function adds an amount of days, months, years, hours and seconds to a DateTime object. This function works in PHP 5.3.0 and above version. It returns no value. 

Description

void date_add ( DateTime $object , DateInterval $interval )

Adds the specified DateInterval object to the specified DateTime object.

Parameters

object - A date as returned by DateTime.

internal - The amount to be added. For the date use "P3D", "P3M", "P3Y" or a combination of the three e.g. "P2M5D" (Y = Years, M = Months, D = Days.) 

MUST BE YEAR MONTH DAY FORMAT "P5Y", "P5M2D", "P5Y4D". 

For the time use "T3H", "T3M", "T3S" or or a combination of the three e.g. "T5H20M" (H = Hours, M = Minutes, S = Seconds). 

For dateTime use "P5D2M4YT5H20M". The digit before the letter (NOT P or T) can be any amount.

Example:

<?php

$date = new DateTime("24-Aug-2009 13:10:22");
echo $date->format("d-m-Y H:i:s").'<br />';

date_add($date, new DateInterval("P5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days';

date_add($date, new DateInterval("P5M"));
echo '<br />'.$date->format("d-m-Y").' : 5 Months';

date_add($date, new DateInterval("P5Y"));
echo '<br />'.$date->format("d-m-Y").' : 5 Years';

date_add($date, new DateInterval("P5Y5M5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_add($date, new DateInterval("P5YT5H"));
echo '<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>

 

Ads