Search code examples
phpdateleap-year

making php functions to count specific day


I have a function that calculate how many days in 1 year and I got it to work from Monday to Saturday by changing the $week variable from :

Monday - 6:Saturday, but it will not work when I put 7: Sunday.

can anyone help out. am I missing any logic?

$year = 2016;
$newyear = $year;
$week = 0;
$day = 0;
$mo = 1;
$days = array();
$i = 1;

        while ($week != 7) { // here is where I change the 1-7 for days
          $day++;
          $week = date("w", mktime(0, 0, 0, $mo,$day, $year));
        }

        array_push($days,date("r", mktime(0, 0, 0, $mo,$day, $year)));
        while ($newyear == $year) {
          $x =  strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" . $i . " week");
          $i++;
          if ($year == date("Y",$x)) {
            array_push($days,date("r", $x));
          }
          $newyear = date("Y",$x);
        }

        print count($days);

thank you for the help cheers! and would be possible to count immediately 2 years of total days like example :

I have a date which is 11 january 2016 that is monday, and I wanted to know how many days are there from 11 january 2016 to 11january 2018, how many mondays are there.

thank you!


Solution

  • $date_1 =  strtotime("2016-01-11");
    $date_2 = strtotime("2018-01-11");
    $datediff = $date_2 - $date_1;
    echo floor($datediff/(60*60*24));
    

    Modified :

    You can find any day of week between two dates. just change value of $days[0];

    For Monday :

    <?php
    $date_1 = $from = strtotime('2016-01-11');
    $date_2 = strtotime('2018-01-11');
    $days = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
    $count = 0;
    while ($date_1 < $date_2) {
      if(date('l', $date_1) == $days[0]);
      {
        $count++;   
      }
      $date_1 += 7 * 24 * 3600;
    }
    echo "From : ".date('Y-m-d',$from)."  To : ".date('Y-m-d',$date_2)."  has $count  $days[0]";
    ?>
    

    OUTPUT :

    From : 2016-01-11 To : 2018-01-11 has 105 Monday