2017-08-03 65 views
-1

我在本地捕捉当月的第一天和最后一天。然后,我想要更进一步,减去12个月,这样我就可以在12个月前和11个月前获得本月的第一天和最后一天。我的问题是,语法永远不会从当前月份改变。以下全部结果产生08/01/2017和08/31/2017获得12个月前在PHP

这应该如何改变,以便它产生准确的结果?

$firstdayofmonth = date('Y-m-01'); 
$lastdayofmonth = date('Y-m-t'); 

$firstdayofmonth = date('m-d-Y', strtotime($firstdayofmonth)); 
$lastdayofmonth = date('m-d-Y', strtotime($lastdayofmonth)); 

$month12start = date($firstdayofmonth, strtotime("-12 months")); 
$month12end = date($lastdayofmonth, strtotime("-12 months")); 
$month11start = date($firstdayofmonth, strtotime("-11 months")); 
$month11end = date($lastdayofmonth, strtotime("-11 months")); 

echo $month12start; 
echo $month12end; 
echo $month11start; 
echo $month11end; 
+0

您通过()'的变量,从'日期是一个字符串到一个新的'日期()'调用的格式参数 - 这没有多大意义。 – Qirel

+0

'$ month12start = date('08 -01-2017',strtotime(“ - 12 months”))'没有日期格式的字符,你不会有任何改变。 –

+0

@Qirel - 你会如何推荐我设置它? – BellHopByDayAmetuerCoderByNigh

回答

2

strtotime()是不是在PHP最可靠的方法日期,可以有一些奇怪的行为,在这里看到的 - Removing exactly one month from a date

我反而建议你使用DateTime()像这样:

$date = new DateTime(); //Today 
$lastDay = $date->format("Y-m-t"); //Get last day 
$dateMinus12 = $date->modify("-12 months"); // Last day 12 months ago 
+0

如果我添加一个echo $ dateMinus12;到http://www.writephponline.com/语法和测试的结尾没有什么是回声 – BellHopByDayAmetuerCoderByNigh

+0

尝试'echo $ dateMinus12-> format('Ym-d');' – DrRoach

+0

为什么这回去2 y $ date = new DateTime(); //今日 $ dateMinus12 = $ date-> modify(“ - 12 months”); //最后一天12个月前 $ dateMinus12end = $ date-> modify(“ - 12 months”); echo $ dateMinus12-> format('Y-m-01'); echo $ dateMinus12end-> format('Y-m-t'); ear and present 2015-08-01 and 2015--8-31 ???? – BellHopByDayAmetuerCoderByNigh

相关问题