Reputation: 13
I'm looking for a solution for the following:
$date = new DateTime('02/29/2020');
$date->sub(new DataInterval('P1Y'));
$date->format('m/d/Y');
This Returns: 03/01/2019
Is there a way to return 02/28/2019? Thanks
Upvotes: 1
Views: 478
Reputation: 12374
date('L')
returns true if a leap year, so:
<?php
$date = new DateTime('02/29/2020');
$date->format('L') && $date->format('m-d') == '02-29' ? 'P366D' : 'P1Y';
$date->sub(new DateInterval($interval));
echo $date->format('m/d/Y');
Check it out here https://3v4l.org/4mXX4
Upvotes: 2
Reputation: 7703
The challenge is general: Add or subtract a month to a date without jumping to the next month if the date is close to the end of the month. For a year, this is to add or subtract 12 months.
The algorithm for the addMonthCut() function was taken here.
function addMonthCut(DateTime $date,$month = 1) {
$dateAdd = clone $date;
$dateLast = clone $date;
$strAdd = ' '.(int)$month.' Month';
$strLast = 'last Day of '.(int)$month.' Month';
if ($dateAdd->modify($strAdd) < $dateLast->modify($strLast)) {
$date->modify($strAdd);
}
else {
$date->modify($strLast);
}
return $date;
}
Examples:
$date = new DateTime('02/29/2020');
$date = addMonthCut($date,-12); //-1 Year
echo $date->format('m/d/Y'); //02/28/2019
$date = new DateTime('02/28/2019');
$date = addMonthCut($date,+12); //+1 Year
echo $date->format('m/d/Y'); //02/28/2020
$date = new DateTime('01/31/2020');
$date = addMonthCut($date,+1); //+1 Month
echo $date->format('m/d/Y'); //02/29/2020
Upvotes: 0