Home  >  Article  >  Backend Development  >  关于PHP中时间计算的"-1 month"?

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

WBOY
WBOYOriginal
2016-06-06 20:41:551213browse

今天,也就是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>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn