Adding Days To $Date In PHP
Answer :
All you have to do is use days
instead of day
like this:
<?php $Date = "2010-09-17"; echo date('Y-m-d', strtotime($Date. ' + 1 days')); echo date('Y-m-d', strtotime($Date. ' + 2 days')); ?>
And it outputs correctly:
2010-09-18 2010-09-19
If you're using PHP 5.3, you can use a DateTime
object and its add
method:
$Date1 = '2010-09-17'; $date = new DateTime($Date1); $date->add(new DateInterval('P1D')); // P1D means a period of 1 day $Date2 = $date->format('Y-m-d');
Take a look at the DateInterval
constructor manual page to see how to construct other periods to add to your date (2 days would be 'P2D'
, 3 would be 'P3D'
, and so on).
Without PHP 5.3, you should be able to use strtotime
the way you did it (I've tested it and it works in both 5.1.6 and 5.2.10):
$Date1 = '2010-09-17'; $Date2 = date('Y-m-d', strtotime($Date1 . " + 1 day")); // var_dump($Date2) returns "2010-09-18"
From PHP 5.2 on you can use modify with a DateTime object:
http://php.net/manual/en/datetime.modify.php
$Date1 = '2010-09-17'; $date = new DateTime($Date1); $date->modify('+1 day'); $Date2 = $date->format('Y-m-d');
Be careful when adding months... (and to a lesser extent, years)
Comments
Post a Comment