简体   繁体   English

PHP日期strtotime无法正常工作

[英]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? 我希望将$days (15天)添加到日期( 2012-04-12 )我期待得到2012-04-27并且此代码返回2012-04-12 ,我做错了什么?

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

Don't use strtotime(). 不要使用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. 但依赖于strtotime仍然是一件坏事,因为它会让你的生活在某些时候变得悲惨。

Use DateTime instead: 改为使用DateTime

$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? 为什么不直接使用DateTime类?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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