5

I wrote this piece of code

echo date("Y-m-d", strtotime($date, strtotime("+ " . $days . " days")));

$date = 2012-04-12
$days = 15

I am looking to add $days (15 days) to the date (2012-04-12) I am expecting to get 2012-04-27 and this code returns me 2012-04-12, what am I doing wrong?

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
user979331
  • 11,039
  • 73
  • 223
  • 418

6 Answers6

8
echo date('Y-m-d', strtotime('+15 days', strtotime('2012-04-12')));
Nate
  • 1,303
  • 8
  • 12
5

Don't use strtotime(). It's unreliable, though you're not really doing anything that would really come back to bite you in the rump. But depending on strtotime is still a bad thing, because it WILL make your life miserable at some point.

Use DateTime instead:

$now = DateTime::CreateFromFormat('Y-m-d', '2012-04-12');
$then = $now->add(new DateInterval('P15D'));
$date = $then->format('Y-m-d');
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 6
    `strtotime()` is not unreliable; in fact, DateTime class uses it under the sheets. – Daniel Ribeiro Apr 12 '12 at 18:17
  • Yeah, if you're the auto-detection stuff. But if you've got a known-format date, then don't use strtotime at all. – Marc B Apr 12 '12 at 18:18
  • 2
    I agree with you in principle, Marc, but I question the necessity of instantiating an object to do something so trivial. If he were going to be doing timezone changes or other more advanced operations, yeah use the object, absolutely. To simply add a few days? Meh. – Chris Baker Apr 12 '12 at 18:20
2
$date = '2012-04-12';
$days = 15;
echo date('Y-m-d', strtotime("$date +$days days") );
MetalFrog
  • 9,943
  • 1
  • 22
  • 24
1
echo date("Y-m-d", strtotime("+$days days", $date));
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
1

Your syntax is incorrect. It isn't necessary or even helpful to place your code all on one line. In this case, we see that trying to do so causes syntax problems. Don't be afraid of a couple of extra little variables!

$date = '2012-04-12';
$days = 15;

$ts = strtotime($date);
$new_ts = strtotime('+'.$days.' days', $ts);
$new_date = date('Y-m-d', $new_ts);

Clear, easy to read, easy to debug. If you like code golf, you CAN put it in one line, but there's a clearer way to write it:

$new_date = date (
    'Y-m-d',
    strtotime (
        '+'.$days.' days',
        strtotime($date)
    )
);

Documentation

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
0

Why not just use DateTime class?

$date = new DateTime();
$date->add(new DateInterval('P15D'));
Daniel Ribeiro
  • 10,156
  • 12
  • 47
  • 79