我正在 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;
Run Code Online (Sandbox Code Playgroud)
strtotime()不是 PHP 中最可靠的日期方法,并且可能有一些奇怪的行为,请参阅此处 -从日期中删除一个月。
我建议您DateTime()像这样使用:
$date = new DateTime(); //Today
$lastDay = $date->format("Y-m-t"); //Get last day
$dateMinus12 = $date->modify("-12 months"); // Last day 12 months ago
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5885 次 |
| 最近记录: |