【发布时间】:2017-08-03 13:56:31
【问题描述】:
我正在 php 中捕获当前月份的第一天和最后一天。然后我想更进一步,减去 12 个月,这样我就可以得到 12 个月前和 11 个月前一个月的第一天和最后一天。我的问题是语法永远不会从当前月份改变。以下所有结果均产生 08/01/2017 和 08/31/2017
应该如何改变它才能产生准确的结果?
$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;
【问题讨论】:
-
您将一个来自
date()的字符串变量传递给新的date()调用的格式参数 - 这没有多大意义。 -
$month12start = date('08-01-2017', strtotime("-12 months"))没有日期格式字符,您不会得到任何更改。 -
@Qirel - 你会建议我如何设置它?
-
我是从移动 atm 写的,所以编写代码有点困难 - 但基本上你将日期字符串而不是有效格式传递给
date(),这就是失败的原因。你会得到类似date("08-01-2017")的东西,它应该是你的前四行。 -
看看 Carbon 库:carbon.nesbot.com。它具有选择月份的开始和结束,减去月份等方法。
标签: php