2012-05-31 93 views
0

可能重复:
PHP date() and strtotime() return wrong months on 31st什么事会发生在PHP的日期功能

我有这样的代码,它输出一些奇怪的事情,我认为。所以,我在这里做错了什么。

<?php 
$sP1 = date('m Y'); 
$sP2 = date('m Y', strtotime('+01 month')); 
$sP3 = date('m Y', strtotime('+02 month')); 
$sP4 = date('m Y', strtotime('+03 month')); 
echo $sP1.'<br>'; 
echo $sP2.'<br>'; 
echo $sP3.'<br>'; 
echo $sP4.'<br>'; 
?> 

这个输出

05 2012 
07 2012 
07 2012 
08 2012 

我认为第二个应该是

06 2012 

有人知道任何解决办法吗?

+1

见在这个问题上接受的答案:http://stackoverflow.com/questions/9058523/php-date-and-strtotime-return-wrong -months-on-31st – Andy

+0

非常感谢你.. :) – Prashank

回答

2

今天是第31个下个月仅在30天内所以这将是7/12 1个月内从今天

assuming that today is May 31 2012 

date('m Y') == 05 2012 
date('m Y', strtotime('+1 month')) == 07 2012 because june has 30 days 
date('m Y', strtotime('+2 month')) == 07 2012 
date('m Y', strtotime('+3 month')) == 08 2012 
date('m Y', strtotime('+4 month')) == 10 2012 

我会采取今天的日期,并找到该月的第一天,然后加了一个月如果你正在做的事情需要得到每个月

1

它正在按预期工作。简而言之,这是因为5月31日的“一个月”是什么? 6月30日? 8月1日?

我的建议是,如果你需要连续几个月,计算从当前月份开始的偏移量,而不是当前日期。或者使用分解的月份,日期和年份手动编写要查找的日期。

+2

你对7月份的穷人做了什么? :( – Andy

2

正如其他人所说,这是因为今天是第31和+1个月等于6月31日,其变化为7月1日。如果您在日期字符串中包含该日期,则可以看到这一点。

<?php 
$sP1 = date('m-d-Y'); 
$sP2 = date('m-d-Y', strtotime('+01 month')); 
$sP3 = date('m-d-Y', strtotime('+02 month')); 
$sP4 = date('m-d-Y', strtotime('+03 month')); 
echo $sP1."\n"; 
echo $sP2."\n"; 
echo $sP3."\n"; 
echo $sP4."\n"; 
/* Outputs: 
    05-31-2012 
    07-01-2012 
    07-31-2012 
    08-31-2012 
*/ 
?> 

strtotime尽管可以将开始日期作为字符串的一部分,所以King建议,从第一个月开始计算+ N个月。因此,像一个字符串May-1-2012 +01 month如:

<?php 
$sP1 = date('m Y'); 
$sP2 = date('m Y', strtotime(date('M-1-Y').' +01 month')); 
$sP3 = date('m Y', strtotime(date('M-1-Y').' +02 month')); 
$sP4 = date('m Y', strtotime(date('M-1-Y').' +03 month')); 
echo $sP1."\n"; 
echo $sP2."\n"; 
echo $sP3."\n"; 
echo $sP4."\n"; 
/* Outputs: 
    05 2012 
    06 2012 
    07 2012 
    08 2012 
*/ 
?> 

http://codepad.org/auYLHvDI