I am trying to figure out how to calculate the closest date after a given date for a recurring period.
For example, if the recurring period is every two weeks, starting Jan 1st 2016 and the given date is Jan 17, how do I calculate that the next recurring period date is Jan 28th?
The recurring period could be any number of days, weeks, months or years.
Right now the only solution I can think of is to start at the starting date and loop, adding the recurring period on each iteration until I pass the given date, but I am wondering if there is a more efficient or elegant solution?
You can use DatePeriod to accomplish it:
$begin = new DateTime('2016-01-01');
$end = new DateTime('2016-12-31');
$interval = new DateInterval('P14D');
$datePeriod = new DatePeriod($begin, $interval ,$end);
$givenDate = new DateTime('2016-01-17');
foreach ($datePeriod as $date) {
if ($date < $givenDate) {
continue;
}
echo 'The next recurring period date is ' . $date->format('Y-m-d');
break;
}
The output would be:
The next recurring period date is 2016-01-29
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With