muncherelli
muncherelli

Reputation: 2903

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 this be achieved in PHP?

Upvotes: 0

Views: 458

Answers (4)

Saic Siquot
Saic Siquot

Reputation: 6513

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;
}

?>

Upvotes: 0

Dr.Molle
Dr.Molle

Reputation: 117314

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

Upvotes: 1

krasnerocalypse
krasnerocalypse

Reputation: 966

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.

Upvotes: 0

SDuke
SDuke

Reputation: 437

Look at the time function for php.

Upvotes: 0

Related Questions