views:

220

answers:

3

Hello! 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

+4  A: 

This should do:

echo date('d.m.Y', strtotime('next Sunday', strtotime('07.05.2010')));
Mike
Not if the latter is a german date format MM.DD.YYYY - strtotime will screw that up. You'll have to find a solution for that as well to get my upvote :)
Pekka
Plus, be sure to test out the edge cases. What happens if 07.05.2010 itself is a sunday?
Pekka
"next Sunday" is not necessarily the "nearest Sunday"
Dolph
ask your users to inpt the date in the proper format .. otherwise u cant find out if its 05/07 or 07/05 that the user entered
Aviatrix
Thanks, it worked even if the date is a Sunday too. Shame on me of not knowing this 'next %dayofweek%' method for 'strtotime'...
moogeek
So by *nearest* you actually meant *next* ?
salathe
+1  A: 

strtotime is magical

echo date("d/m/y", strtotime("next sunday", strtotime("07.05.2010")  ) );
Galen
Who's to say that *next* Sunday is the nearest?..
salathe
+4  A: 

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");
salathe
geez, I was overcomplicating things. Nice +1
Gordon
you'll like my edit then :-)
salathe