S_R
S_R

Reputation: 1998

Next Occurance of day and month

I want to be able to find the next occurrence of a date when I give it just the date and month. I have found answers on how to find 'next monday' or how to do this in another language, but I cant figure out how to do it PHP!

For example, if the date I give a function is 2019-07-04 (Y-m-d), on 2019-07-03, the date returned will still be 2019-07-04, but on 2019-07-04, the next occurrence will be 2020-07-04.

So if I give it the date of the 3rd of July, I want to know the next time that date occurs? If its tomorrow or 364 days, just when it comes up next?

Upvotes: 0

Views: 106

Answers (2)

Álvaro González
Álvaro González

Reputation: 146630

I've honestly been unable to compose a working relative format for strtotime(), which would be the elegant one-liner we all dream of, so I've composed a poor-man's loop:

/**
 * @param int $month
 * @param int $day
 * @param int $reference Unix time, defaults to today
 * @return int Unix time
 */
function nextOcurrence($month, $day, $reference = null)
{
    if ($reference === null) {
        $reference = mktime(0, 0, 0);
    }
    $year = date('Y', $reference);
    while (!checkdate($month, $day, $year) || ($date = mktime(0, 0, 0, $month, $day, $year)) <= $reference){
        $year++;
    }
    return $date;
}

Highlights:

  • "Today" is not hard-coded to ease testing.
  • It takes leap years into account but not Popes fiddling with the calendar.
  • It uses Unix timestamps so it cannot handle dates prior to 1970 in 32-bit PHP.
  • Dates are hard so it's probably wrong.

Demo.

Upvotes: 0

Dharman
Dharman

Reputation: 33395

You can just check if the date you have is more than today and keep it, or increase by one year.

function nextDate($day, $month){
    $dateObj = DateTime::createFromFormat('m-d', $month.'-'.$day);
    $today = new \DateTime();
    if($dateObj > $today){
        return $dateObj;
    }
    return $dateObj->modify('+ 1 year');
}

https://ideone.com/Nf9HWh

Upvotes: 3

Related Questions