Reputation: 457
I have a problem like this. For a given date I need to get the last day of each of the previous months up to 5 months. As an example, if the input date is 2018-08-21, then the result I want is something like (2018-07-31,2018-06-30,2018-05-31,2018-04-30,2018-03-31)
I wrote a for loop to iterate for 5 times and used the following code to get the previous month. But at months of 31 days, it doesn't exactly give the previous month. It gives the last day as "2011-07-31" which is not true. Is there a workaround for this one??
$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)
Upvotes: 1
Views: 306
Reputation: 910
Try to use DateTime
Classe. You can run this in a loop like following
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);
}
Upvotes: 0
Reputation: 183
requirement could be achieved by using loop with use of DateTime. If am right in understating please try
$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;
Upvotes: 0
Reputation: 527
For solve that problem you can try this
<?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
?>
Upvotes: 0
Reputation: 7171
try with this
echo date('2011-07-31', strtotime('last day of previous month'));
//2011-06-30
or
<?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);
}
?>
Upvotes: 1
Reputation: 1529
Simple and easy to understand. Try this :-
$initialDate = "2011-07-31";
for($i=1; $i<=5; $i++) {
echo date('Y-m-d', strtotime('last day of -' . $i . ' month', strtotime($initialDate))) . "<br>";
}
Check this Fiddle link
Upvotes: 3