how to find number of mondays or tuesdays between two dates?

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

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?

回答1:

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 :)



回答2:

no loops and no recursivity

<?php define('ONE_WEEK', 604800); // 7 * 24 * 60 * 60  function number_of_days($days, $start, $end) {     $w = array(date('w', $start), date('w', $end));     $x = floor(($end-$start)/ONE_WEEK);     $sum = 0;      for ($day = 0;$day < 7;++$day) {         if ($days & pow(2, $day)) {             $sum += $x + ($w[0] > $w[1]?$w[0] <= $day || $day <= $w[1] : $w[0] <= $day && $day <= $w[1]);         }     }      return $sum; }  //$start = $end = time();  // 0x10 == pow(2, 4) == 1 << 4 // THURSDAY // 0x20 == pow(2, 5) == 1 << 5 // FRIDAY echo number_of_days(0x01, $start, $end); // SUNDAY echo number_of_days(pow(2, 0), $start, $end); // SUNDAY echo number_of_days(0x02, $start, $end); // MONDAY echo number_of_days(pow(2, 1), $start, $end); // MONDAY echo number_of_days(0x04, $start, $end); // TUESDAY echo number_of_days(1 << 2, $start, $end); // TUESDAY echo number_of_days(0x08, $start, $end); // WEDNESDAY echo number_of_days(1 << 3, $start, $end); // WEDNESDAY echo number_of_days(0x10, $start, $end); // THURSDAY echo number_of_days(0x20, $start, $end); // FRIDAY echo number_of_days(0x40, $start, $end); // SATURDAY echo number_of_days(0x01 | 0x40, $start, $end); // WEEKENDS : SUNDAY | SATURDAY echo number_of_days(0x3E, $start, $end); // WORKDAYS : MONDAY | TUESDAY | WEDNESDAY | THURSDAY | FRIDAY ?> 


回答3:

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:

/**  * Counts the number occurrences of a certain day of the week between a start and end date * The $start and $end variables must be in UTC format or you will get the wrong number  * of days  when crossing daylight savings time * @param - $day - the day of the week such as "Monday", "Tuesday"... * @param - $start - a UTC timestamp representing the start date * @param - $end - a UTC timestamp representing the end date * @return Number of occurences of $day between $start and $end */ 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 UTC");     $end = strtotime("3 tuesday UTC");        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.



回答4:

This question is just crying out for an updated answer that uses PHP's DateTime classes, so here it is:-

/**  * @param String $dayName eg 'Mon', 'Tue' etc  * @param DateTimeInterface $start  * @param DateTimeInterface $end  * @return int  */ function countDaysByName($dayName, \DateTimeInterface $start, \DateTimeInterface $end) {     $count = 0;     $interval = new \DateInterval('P1D');     $period = new \DatePeriod($start, $interval, $end);      foreach($period as $day){         if($day->format('D') === ucfirst(substr($dayName, 0, 3))){             $count ++;         }     }     return $count; } 


回答5:

<?php $date = strtotime('2009-01-01'); $dateMax = strtotime('2009-02-23');  $nbr = 0; while ($date < $dateMax) {   var_dump(date('Y-m-d', $date));   $nbr++;   $date += 7 * 24 * 3600; } echo "<pre>";  var_dump($nbr); ?> 


回答6:

To count The Total Friday Between Two Dates##

$from_date=(2015-01-01);  $to_date=(2015-01-20);  while(strtotime($from_date) <= strtotime($to_date)){      //5 for count Friday, 6 for Saturday , 7 for Sunday      if(date("N",strtotime($from_date))==5){         $counter++;     }     $from_date = date ("Y-m-d", strtotime("+1 day", strtotime($from_date)));  }  echo $counter; 


回答7:

function daycount($day, $startdate, $enddate, $counter) {     if($startdate >= $enddate) {         return $counter-1;  // A hack to make this function return the correct number of days.     } else {         return $this->daycount($day, strtotime("next ".$day, $startdate), $enddate, ++$counter);     } } 

This is a different version of the first answer which takes a start and end point and works for me. All of the examples given on this page seemed to return the answer plus an additional day for some reason.



回答8:

w35l3y's answer seems to work well, so I up-voted it. Still, I preferred something a bit easier to follow, and with less math and looping (not sure it matters from a performance standpoint, though). I think I covered all the possible scenarios... Here's what I came up with:

function numDays($sday, $eday, $i, $cnt) {     if (($sday < $eday && $i >= $sday && $i <= $eday) || ($sday > $eday && ($i >= $sday || $i <= $eday))) {         // partial week (implied by $sday != $eday), so $i (day iteration) may have occurred one more time         // a) end day is ahead of start day; $i is within start/end of week range         // b) start day is ahead of end day (i.e., Tue start, Sun end); $i is either in back half of first week or front half of second week         $cnt++;     } elseif ($sday == $eday && $i == $sday) {         // start day and end day are the same, and $i is that day, i.e., Tue occurs twice from Tue-Tue (1 wk, so $wks = $cnt)         $cnt++;     }      return $cnt;    // # of complete weeks + partial week, if applicable } 

Notes: $sday and $eday are the day numbers corresponding to the start and end of the range to be checked, and $i is the day number being counted (I have it in a 0-6 loop). I moved $wks outside the function, as there's no point recalculating it each time.

$wks = floor(($endstamp - $startstamp)/7*24*60*60); $numDays = numDays($sday, $eday, $i, $wks); 

Make sure the start/end timestamps you're comparing have the same timezone adjustment, if any, otherwise you'll always be off a bit with $cnt and $wks. (I ran into that when counting from an unadjusted first of the year to an adjusted day/time X.)



回答9:

Correct day count. This will count all the Days from Monday to Sunday between 2 given date

 <?php      $startdate='2018-04-01';     $enddate='2018-04-20';      $mondayCount = 0;     $tuesday = 0;     $wednesday = 0;     $thursday = 0;      $friday = 0;     $saturday = 0;     $sunday = 0;      $begin = new DateTime($startdate );     $end = new DateTime( $enddate );     $end = $end->modify( '+1 day' );      $interval = new DateInterval('P1D');     $daterange = new DatePeriod($begin, $interval ,$end);     // looping each days from FROM and TO dates      foreach($daterange as $date) {         //$eachDate = $date->format("d-m-Y");         echo $eachDateName = $date->format("l");         switch ($eachDateName)         {             case 'Monday' :                 $mondayCount++;break;             case 'Tuesday' :                 $tuesday++;break;             case 'Wednesday' :                 $wednesday++;break;             case 'Thursday' :                 $thursday++;break;             case 'Friday' :                 $friday++;break;             case 'Saturday' :                 $saturday++;break;             case 'Sunday' :                 $sunday++;break;         }      }     echo $mondayCount;echo "---";     echo $tuesday;echo "---";     echo $wednesday;echo "---";     echo $thursday;echo "---";     echo $friday;echo "----";     echo $saturday;echo "---";     echo $sunday; ?> 

Hope this will help someone



回答10:

I got the answer.Its working for sunday only.But I dont know how to make it for another days

"; $days_until_sunday = date('w', $start) > 0 ? 7 - date('w', $start) : 0; $date = $start + (ONE_DAY * $days_until_sunday); $sundays = array(); while ($date "; $count=0; // Loop and output Y-m-d foreach (sundays_in_range($start, $end) as $sunday) { print "".date("Y-m-d", $sunday)."
"; $count++; } echo $count; ?>


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!