Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find nearest day of week in php?

How to find a speciefic nearest day of the week in PHP if initially I have a date string like: 07.05.2010? For example, I want to find the nearest Sunday (or any day of the week). How can I implement this? Thanks

like image 429
moogeek Avatar asked May 06 '10 21:05

moogeek


2 Answers

/**
 *
 * @param \DateTime $date
 * @param $dayOfWeek - e.g Monday, Tuesday ...
 */
public function findNearestDayOfWeek(\DateTime $date, $dayOfWeek)
{
    $dayOfWeek = ucfirst($dayOfWeek);
    $daysOfWeek = array(
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday',
        'Sunday',
    );
    if(!in_array($dayOfWeek, $daysOfWeek)){

        throw new \InvalidArgumentException('Invalid day of week:'.$dayOfWeek);
    }
    if($date->format('l') == $dayOfWeek){

        return $date;
    }

    $previous = clone $date;
    $previous->modify('last '.$dayOfWeek);

    $next = clone $date;
    $next->modify('next '.$dayOfWeek);

    $previousDiff = $date->diff($previous);
    $nextDiff = $date->diff($next);

    $previousDiffDays = $previousDiff->format('%a');
    $nextDiffDays = $nextDiff->format('%a');

    if($previousDiffDays < $nextDiffDays){

        return $previous;
    }

    return $next;
}

Alternatively you could create a map of what days of weeks are closer, e.g if you're after closest Monday to Wednesday, it would be faster to just find the previous Monday given that it's closer than the next Monday.

like image 168
Rob Jensen Avatar answered Nov 16 '22 02:11

Rob Jensen


This should do:

echo date('d.m.Y', strtotime('next Sunday', strtotime('07.05.2010')));
like image 36
Mike Avatar answered Nov 16 '22 02:11

Mike