[英]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)
簡單易懂。 嘗試這個 :-
$initialDate = "2011-07-31";
for($i=1; $i<=5; $i++) {
echo date('Y-m-d', strtotime('last day of -' . $i . ' month', strtotime($initialDate))) . "<br>";
}
檢查此小提琴鏈接
試試這個
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
Classe。 您可以像下面這樣循環運行
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);
}
為了解決這個問題,你可以嘗試一下
<?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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.