Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the closest date for a recurring period, after a given date (PHP)

Tags:

date

php

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?

like image 613
Ben Holness Avatar asked May 27 '16 11:05

Ben Holness


1 Answers

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

like image 171
Mihai Matei Avatar answered Oct 16 '22 17:10

Mihai Matei