>  기사  >  백엔드 개발  >  PHP 关于strtotime(" x month") bug的解决

PHP 关于strtotime(" x month") bug的解决

WBOY
WBOY원래의
2016-06-13 13:12:101029검색

PHP 关于strtotime("- x month") bug的解决


strtotime('-x month'); 在涉及到月份修改的时候,可能不会得到预料的结果。

此为php的一个bug:

https://bugs.php.net/bug.php?id=27793

?

如:当前时间为: 2011-08-31 17:21:22

date_default_timezone_set('Asia/Shanghai');
$t = time();
print_r(array(
??? ??? ??? date('Y年m月',$t),
??? ??? ??? date('Y年m月',strtotime('- 1 month',$t)),
??? ??? ??? date('Y年m月',strtotime('- 2 month',$t)),
));

?>

上面代码输出:

Array
(
??? [0] => 2011年08月
??? [1] => 2011年07月
??? [2] => 2011年07月
)

而预期的结果是:

Array
(
??? [0] => 2011年08月
??? [1] => 2011年07月
??? [2] => 2011年06月
)

?

============================================

?

可以用如下方法解决:

date_default_timezone_set('Asia/Shanghai');

$first_day_of_month = date('Y-m',time()) . '-01 00:00:01';
$t = strtotime($first_day_of_month);
print_r(array(
??? ??? ??? date('Y年m月',$t),
??? ??? ??? date('Y年m月',strtotime('- 1 month',$t)),
??? ??? ??? date('Y年m月',strtotime('- 2 month',$t)),
));

?>

输出:

Array
(
??? [0] => 2011年08月
??? [1] => 2011年07月
??? [2] => 2011年06月
)

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.