我有这样的问题。对于给定的日期,我需要使前几个月的每个月的最后一天(最多5个月)达到目标。 例如,如果输入日期为2018-08-21,则我想要的结果类似于(2018-07-31,2018-06-30,2018-05-31,2018-04-30,2018- 03-31)
我编写了一个for循环以进行5次迭代,并使用以下代码获取了上个月的代码。但是在31天的月份中,它并不完全是上个月。它给出的最后一天是“ 2011-07-31”,这是不正确的。有没有解决方法?
$datetocheck = "2011-07-31";
$lastday = date('Y-m-t', strtotime('-1 month', strtotime($datetocheck)));
echo $lastday; //this gives 2011-07-31(Expected value is 2011-06-30)
答案 0 :(得分:3)
简单易懂。试试这个:-
$initialDate = "2011-07-31";
for($i=1; $i<=5; $i++) {
echo date('Y-m-d', strtotime('last day of -' . $i . ' month', strtotime($initialDate))) . "<br>";
}
选中此Fiddle链接
答案 1 :(得分:1)
尝试
echo date('2011-07-31', strtotime('last day of previous month'));
//2011-06-30
或
<?php
$date = '2011-07-31';
$date = new DateTime($date);
for($i=0;$i<5;$i++){
$date->modify("last day of previous month");
echo $date->format("Y-m-d")."<br>";
$newDate= $date->format("Y-m-d");
$date=new DateTime($newDate);
}
?>
答案 2 :(得分:0)
尝试使用DateTime
类。您可以像下面这样循环运行
function lastDayOfMonth($datetocheck, $noOfMonth){
$date = new \DateTime($datetocheck);
$month = ((int) ($date)->format('m'))-$noOfMonth;
$year = ($date)->format('Y');
$lastMonth = new \DateTime("{$year}-{$month}");
$lastday = $lastMonth->format('Y-m-t');
echo $lastday . PHP_EOL;
}
for($i = 1; $i <= 5; $i++){
lastDayOfMonth('2011-07-31', $i);
}
答案 3 :(得分:0)
要解决该问题,您可以尝试
<?php
$datetocheck = "2011-07-31";
$tmp_date = date('Y-m-01',strtotime($datetocheck));
$lastday = date('Y-m-t', strtotime('-1 month', strtotime($tmp_date)));
echo $lastday; //this value is 2011-06-30
?>
答案 4 :(得分:0)
要求可以通过使用带有DateTime的循环来实现。如果低估是正确的,请尝试
$startDate = new DateTime('2018-08-21');
$dateArr = array();
for($i=0; $i<=4; $i++) {
$date = $startDate;
$date->modify("last day of previous month");
$lastDateOfMonth = $date->format("Y-m-d");
$dateArr[] = $lastDateOfMonth;
$startDate = new DateTime($lastDateOfMonth);
}
$dateList = implode(",", $dateArr);
echo $dateList;