---
title: "PHP 关于strtotime(\"- x month\") bug的解决"
author: "spamer"
date: "2011-08-31T17:22:20Z"
tags: []
categories: ["Web前端"]
slug: "php-strtotime-x-month-bug"
draft: false
lastmod: "2011-08-31T17:22:20Z"
id: 1162625
url: "https://spamer.iteye.com/blog/1162625"
---

```

```

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

此为php的一个bug：

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

 

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

&lt;?php  
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)),  
));

?&gt;

上面代码输出：

Array  
(  
    \[0] =&gt; 2011年08月  
    \[1] =&gt; 2011年07月  
    \[2] =&gt; 2011年07月  
)

而预期的结果是：

Array  
(  
    \[0] =&gt; 2011年08月  
    \[1] =&gt; 2011年07月  
    \[2] =&gt; 2011年06月  
)

 

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

 

可以用如下方法解决：

&lt;?php

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)),  
));

?&gt;

输出：

Array  
(  
    \[0] =&gt; 2011年08月  
    \[1] =&gt; 2011年07月  
    \[2] =&gt; 2011年06月  
)