欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-05-10 20:10:32
...
今天,也就是10月31号,执行一下代码:
echo date('Ym', strtotime("-1 month"));

返回的结果是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号,执行一下代码:

echo date('Ym', strtotime("-1 month"));

返回的结果是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

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

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

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

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

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

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

echo date("Y-m", strtotime("-1 month", strtotime("first day of this month")));
相关标签: php