PHP get same day of same week next year

date, datetime, php

Solution

As has already been pointed out, there may not be a 5th Friday in June, for example, so there needs to be some standard way to decide which week next year is the same week as the current one.

As it happens there is already a standard for week numbering in ISO 8601 and PHP's DateTime class has built in functionality for handling them.

My suggestion would be to schedule the next meeting for the same day in the same `ISO 8601 week number` the following year. The following function will do that for you:-

/**
 * @param \DateTime $date Date of the original meeting
 * @return \DateTime Date of the next meeting
 */
function getSameDayNextYear(\DateTime $date = null)
{
    if(!$date){
        $date = new \DateTime();
    }
    return (new \DateTime())->setISODate((int)$date->format('o') + 1, (int)$date->format('W'), (int)$date->format('N'));
}

See it working with some test code.

I'm sure you'll agree that this is the simplest way of doing it and it should see you right for the next 100 years or more :)

References DateTime and Date for formats.

Problem

I'm working on a client scheduler and my employer wants it to automatically reschedule clients each year. He wants them to keep the same day of the same week every year. For example, a client is scheduled for May 23rd 2014. This is the fourth friday of may. Once May 23rd 2014 has passed, a appointment for the fourth friday of may in 2015 should be booked (in this case the 22nd). I've tried various things to get this to work (such as using DateTime to advance by a year and find "previous" of whatever day of the week it was). But every model I've tried breaks down a bit after just a few years. They'll end up on like...the second Friday of the month. Does anyone have a way to get this to work? My employer is very specific about wanting the scheduler to work this way. x.x I'd really appreciate the help if someone knows how. Thanks for reading this!

Original source