开发者

Find a specific day of week based on a date

I would like to be able to find the date which "Sunday" falls on for a given date, formatted as YYYY-MM-DD.

... How would开发者_Go百科 this be achieved in PHP?


strtotime() may help you, it accepts GNU-Date-input-formats like "next Sunday"

echo date('Y-m-d',strtotime('sunday',strtotime("2011-07-04 Z")));


Look at the time function for php.


If you can't find a library that does this, then:

  1. Come up with a reference date (January 1, 1970?) for which you know the day of the week.
  2. Calculate the number of days between the reference date and your given date.
  3. Take that answer modulo 7.
  4. Convert to a day of the week.


Here you have a full example with multiples values
it is for PHP or any other lenguage that uses epoch time (or similar)

<?php

function prevSunday($paramDay){
    $aDay = 24*60*60;
    $aWeek = $aDay * 7;

    $sunday = $aDay + $paramDay - (($paramDay - 3 * $aDay) % $aWeek);

    return $sunday;
}

$randDay   = 1309819423 + rand(0, 9000000);            //   this contanis a random day (and hours, minutes, seconds)
$aSaterday = strtotime("20110702");
$aSunday   = strtotime("20110703");
$aMonday   = strtotime("20110704");

echoTwoDays($aSuterday, prevSunday($aSuterday));
echoTwoDays($aSunday,   prevSunday($aSunday));
echoTwoDays($aMonday,   prevSunday($aMonday));
/* echoes
day1: Saturday 20110702
day2: Sunday 20110626

day1: Sunday 20110703
day2: Sunday 20110703

day1: Monday 20110704
day2: Sunday 20110703     
*/
echoTwoDays($randDay,   prevSunday($randDay));   // echoes a random date and perv sunday


function echoTwoDays ($day1, $day2) {
    echo "day1: " . date("l Ymd", $day1) ."<br>";      // remove l as your request
    echo "day2: " . date("l Ymd", $day2) ."<br><br>";  // remove l as your request
}

function prevSunday($paramDay){
    $aDay = 24*60*60;
    $aWeek = $aDay * 7;

    $sunday = $aDay + $paramDay - (($paramDay - 3 * $aDay) % $aWeek);

    return $sunday;
}

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜