3

What I am Trying

I am able to get the number of sat&sun between two dates. What I want is to get the number of sat&sun for each month between those dates.

Suppose start_date is 4-Jul-2015 and end_date is 30-Aug-2015. Then there is 8 sat&sun in Jul and 10 in Aug.

From what I did I'm getting 18. But I need to get 8 and 10. How can I get this ?

Code

$countSat = 0;
$countSun = 0;
$start = new DateTime($_POST['start']);
$end   = new DateTime($_POST['end']);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt)
 {
  if ($dt->format('N') == 7)
  {
    $countSun++;
  }
  if ($dt->format('N') == 6)
  {
    $countSat++;
  }
}
$count = $countSat + $countSun;
Avinash
  • 1,935
  • 7
  • 29
  • 55

1 Answers1

1

try this option:

$countSat = 0;
$countSun = 0;
$i = 0;
$start = new DateTime($_POST['start']);
$month = $start->format('n');
$end   = new DateTime($_POST['end']);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt)
{
  if($month != $dt->format('n'))
  {
    $results[$i]=$countSun+$countSat;
    $i++;
    $countSun=0;
    $countSat=0;
  }

  if ($dt->format('N') == 7)
  {
   $countSun++;
  }
  if ($dt->format('N') == 6)
  {
   $countSat++;
  }
  $month = $dt->format('n');
}
Saahon
  • 404
  • 1
  • 6
  • 27
  • could you explain a bit. didnt get it. How will I get the value? – Avinash Oct 29 '15 at 11:00
  • each array element indicates the number of Saturday and Sunday of each month: `for(int $j = 0; $j<$result.length;$j++){ echo "on", $j+1 ," - month of period: ", $result[j] ," sun&sat"; }` – Saahon Oct 29 '15 at 11:03
  • you need to specify the number of the month? For example: a 7-month 8 pieces Saturday + Sunday, an 8-month 10 pieces Saturday + Sunday? – Saahon Oct 29 '15 at 11:24
  • Not getting. The problem is, Aug 30 is sun so if end date is 29 then there will be only 9 in Aug. – Avinash Oct 29 '15 at 11:36