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
views:
220answers:
3
+4
A:
This should do:
echo date('d.m.Y', strtotime('next Sunday', strtotime('07.05.2010')));
Mike
2010-05-06 21:08:01
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
2010-05-06 21:09:29
Plus, be sure to test out the edge cases. What happens if 07.05.2010 itself is a sunday?
Pekka
2010-05-06 21:10:27
"next Sunday" is not necessarily the "nearest Sunday"
Dolph
2010-05-06 21:11:26
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
2010-05-06 21:12:25
Thanks, it worked even if the date is a Sunday too. Shame on me of not knowing this 'next %dayofweek%' method for 'strtotime'...
moogeek
2010-05-06 21:13:07
So by *nearest* you actually meant *next* ?
salathe
2010-05-06 21:43:24
+1
A:
strtotime is magical
echo date("d/m/y", strtotime("next sunday", strtotime("07.05.2010") ) );
Galen
2010-05-06 21:08:23
+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
2010-05-06 21:49:15