获取给定月份的最后一天在 31 天的月份失败

Getting the last day of a given month failing at months of 31 days

我有这样的问题。对于给定的日期,我需要获得前几个月每个月的最后一天最多 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)

试试这个

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);
}
?>

尝试使用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);
}

简单易懂。试试这个:-

$initialDate = "2011-07-31";
for($i=1; $i<=5; $i++) {
    echo date('Y-m-d', strtotime('last day of -' . $i . ' month', strtotime($initialDate))) . "<br>";
}

勾选这个Fiddlelink

要解决这个问题你可以试试这个

<?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
?>

可以通过使用循环和 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;