Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

date - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...