Date Add

WE will learn how to add date time intervals to a date object. We must understand date interval and date format before using add function to the date object.

Note:This will work only if your PHP version is 5.3 or higher

How to know PHP version installed in your server ?

Let us try to add 5 days to current date.

date_default_timezone_set ("Asia/Kolkata");
$date=new DateTime("now") ;
echo $date->format('d-m-y');
echo "<br>";
$date=$date->add(new DateInterval('P5D'));
echo $date->format('d-m-y ');

The output is here

02-07-15
07-07-15

We will add 1 Year, 3 months , 5 days . We will only change the affected row in above code like this.

$date=$date->add(new DateInterval('P1Y3M5D'));
echo $date->format('m-d-y ');

Let us add hour minute and seconds to this date object.

date_default_timezone_set ("Asia/Kolkata");
$date=new DateTime("now") ;
echo $date->format('d-m-y H:i:s');
echo "<br>";
$date=$date->add(new DateInterval('P1Y3M5DT4H5M12S'));
echo $date->format('m-d-y H:i:s ')";

Be the first to post comment on this article :


Google+
Click for more tutorial on Date & Time functions and Applications


More On Date Object

Post Comment This is for short comments only. Use the forum for more discussions.






OPINION POLL

What is the most important factor of a web site
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2015 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer