When manipulating dates, it becomes essential to avoid situations where month end is inadvertently exceeded. This article explores a reliable approach to adding months to a given date while ensuring it remains within the bounds of the target month.
Given a PHP function, the goal is to add a specified number of months to a date without exceeding the month end. The function should adjust the result to the last day of the month if the addition would lead to a spillover.
To achieve the desired functionality, you can utilize the following steps:
function add($date_str, $months)
{
$date = new DateTime($date_str);
$start_day = $date->format('j');
$date->modify(" {$months} month");
$end_day = $date->format('j');
if ($start_day != $end_day)
{
$date->modify('last day of last month');
}
return $date;
}
// Sample tests
$result = add('2011-01-28', 1); // 2011-02-28
$result = add('2011-01-31', 3); // 2011-04-30
$result = add('2011-01-30', 13); // 2012-02-29
$result = add('2011-10-31', 1); // 2011-11-30
$result = add('2011-12-30', 1); // 2011-02-28
By following this approach, you can confidently add months to dates in PHP while adhering to the constraints of month end, ensuring that your results accurately represent the intended time frame.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3