>  기사  >  백엔드 개발  >  关于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으로 문의하세요.