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
Just in case you wanted the nearest day rather than the next one, here is a way to do that.
$target = "Sunday";
$date = "07.05.2010";
// Old-school DateTime::createFromFormat
list($dom, $mon, $year) = sscanf($date, "%02d.%02d.%04d");
$date = new DateTime("$year/$mon/$dom -4 days");
// Skip ahead to $target day
$date->modify("next $target");
echo $date->format("d.m.Y");
And as of PHP 5.3, that middle portion can be simply
$date = DateTime::createFromFormat("!d.m.Y", $date)
->modify("-4 days")->modify("next $target");