首頁  >  文章  >  後端開發  >  关于PHP中时间计算的"-1 month"?

关于PHP中时间计算的"-1 month"?

WBOY
WBOY原創
2016-06-06 20:41:551213瀏覽

今天,也就是10月31号,执行一下代码:

<code>echo date('Ym', strtotime("-1 month"));
</code>

返回的结果是201410,是不是说明类似strtotime("-1 month")是不可信的?

定义了时区。

php -v

PHP 5.4.33-1~dotdeb.0 (cli) (built: Sep 19 2014 12:00:21)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

回复内容:

今天,也就是10月31号,执行一下代码:

<code>echo date('Ym', strtotime("-1 month"));
</code>

返回的结果是201410,是不是说明类似strtotime("-1 month")是不可信的?

定义了时区。

php -v

PHP 5.4.33-1~dotdeb.0 (cli) (built: Sep 19 2014 12:00:21)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

<code>case TIMELIB_MONTH:  s->time->relative.m += amount * relunit->multiplier; break;

月份直接减1 ,当前日期 10月 31号 减一变成  9月31号 即是 10月1号
</code>

这个是php bug,你可以指定月的开始时间。
$base = strtotime(date('Y-m',time()) . '-01 00:00:01');
echo date('m/Y',strtotime('-1 month', $base));

不定义时区真的大丈夫么?定义时区后我这边是正常的,PHP5.5环境。

<code>date_default_timezone_set("Asia/Shanghai");
echo date("Y-m", strtotime("-1 month"));
</code>

可能真的如 @美丽的格调 所说是个BUG(看了下手册不知道是不是5.2.7之处的那个BUG),按照他的说法定义了相对时间后正常了。

<code>echo date("Y-m", strtotime("-1 month", strtotime("first day of this month")));
</code>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn