tags:

views:

344

answers:

4

I have start date and end date.

I need to find out the day that is Sunday or Monday etc dependent upon user click on check box.

How can I find/calculate that in PHP?

A: 
vinothkumar
+3  A: 

You could create a function that uses strtotime() recursively to count the number of days. Since strtotime("next monday"); works just fine.

function daycount($day, $startdate, $counter)
{
 if($startdate >= time())
 {
  return $counter;
 }
 else
 {
  return daycount($day, strtotime("next ".$day, $startdate), ++$counter);
 }
}

echo daycount("monday", strtotime("01.01.2009"), 0);

Hopefully this is something you're looking for :)

Ólafur Waage
Nice and consice, so I scored you +1. However I strtotime() is expensive, as is recursion, so this will run quite slowly for big date ranges. The mathematical version supplied by @w35l3y is much much more efficient code.
Spudley
+1  A: 

no loops and no recursivity

function number_of_days($day, $start, $end)
{
    $w = array(date('w', $start), date('w', $end));

    return floor( ( date('z', $end) - date('z', $start) ) / 7) + ($day == $w[0] || $day == $w[1] || $day < ((7 + $w[1] - $w[0]) % 7));
}

define(ONE_DAY, 86400); // 24 * 60 * 60

$start = time() + 2 * ONE_DAY;
$end = $start + 7 * ONE_DAY;

echo number_of_days(0, $start, $end); // SU
echo number_of_days(1, $start, $end); // MO
echo number_of_days(2, $start, $end); // TU
echo number_of_days(3, $start, $end); // WE
echo number_of_days(4, $start, $end); // TH
echo number_of_days(5, $start, $end); // FR
echo number_of_days(6, $start, $end); // SA
?>
w35l3y
Sweet. Scary looking code though ;) One or two constants might make it easier to read.
Spudley
A: 

The answer by w35I3y was almost correct, but I was getting errors using that function. This function correctly calculates the number of Mondays or any specific day between two given dates:

function countDays($day, $start, $end)
{        
    //get the day of the week for start and end dates (0-6)
    $w = array(date('w', $start), date('w', $end));

    //get partial week day count
    if ($w[0] < $w[1])
    {

        $partialWeekCount = ($day >= $w[0] && $day <= $w[1]);
    }else if ($w[0] == $w[1])
    {
        $partialWeekCount = $w[0] == $day;
    }else
    {
        $partialWeekCount = ($day >= $w[0] || $day <= $w[1]);
    }

    //first count the number of complete weeks, then add 1 if $day falls in a partial week.
    return floor( ( $end-$start )/60/60/24/7) + $partialWeekCount;
}

Example Usage:

$start = strtotime("tuesday");    
$end = strtotime("3 tuesday");       
echo date("m/d/Y", $start). " - ".date("m/d/Y", $end). " has ". countDays(0, $start, $end). " Sundays";

Outputs something like: 09/28/2010 - 10/19/2010 has 3 Sundays.

phil mccull