简体   繁体   中英

PHP date strtotime not working

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?

echo date('Y-m-d', strtotime('+15 days', strtotime('2012-04-12')));

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');
$date = '2012-04-12';
$days = 15;
echo date('Y-m-d', strtotime("$date +$days days") );
echo date("Y-m-d", strtotime("+$days days", $date));

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

Why not just use DateTime class?

$date = new DateTime();
$date->add(new DateInterval('P15D'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM