PHP date strtotime not working
Asked Answered
S

6

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?

Subtitle answered 12/4, 2012 at 18:8 Comment(0)
G
8
echo date('Y-m-d', strtotime('+15 days', strtotime('2012-04-12')));
Grapnel answered 12/4, 2012 at 18:16 Comment(0)
R
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');
Raynell answered 12/4, 2012 at 18:13 Comment(3)
strtotime() is not unreliable; in fact, DateTime class uses it under the sheets.Encircle
Yeah, if you're the auto-detection stuff. But if you've got a known-format date, then don't use strtotime at all.Raynell
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.Sabella
H
2
$date = '2012-04-12';
$days = 15;
echo date('Y-m-d', strtotime("$date +$days days") );
Hoppe answered 12/4, 2012 at 18:15 Comment(0)
T
1
echo date("Y-m-d", strtotime("+$days days", $date));
Tori answered 12/4, 2012 at 18:13 Comment(0)
S
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

Sabella answered 12/4, 2012 at 18:17 Comment(0)
E
0

Why not just use DateTime class?

$date = new DateTime();
$date->add(new DateInterval('P15D'));
Encircle answered 12/4, 2012 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.