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
/**
*
* @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.
This should do:
echo date('d.m.Y', strtotime('next Sunday', strtotime('07.05.2010')));
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