Find out how many Sundays from two given dates?

from 01-01-2009 to 02-23-2009

how to find out how much sunday is between these days?

+2
source share
5 answers

Something like that:

$date = strtotime('2009-01-01 next sunday'); $dateMax = strtotime('2009-02-23'); $nbr = 0; while ($date < $dateMax) { var_dump(date('Ym-d', $date)); $nbr++; $date += 7 * 24 * 3600; } var_dump($nbr); 

And you will get:

 string '2009-01-04' (length=10) string '2009-01-11' (length=10) string '2009-01-18' (length=10) string '2009-01-25' (length=10) string '2009-02-01' (length=10) string '2009-02-08' (length=10) string '2009-02-15' (length=10) string '2009-02-22' (length=10) 

On every Sunday and:

 int 8 

For the number of Sundays

(I quickly checked, and it seems that these dates are really Sunday)


What this code does:

  • first, get the date of the first Sunday after 2009-01-01
  • then if the current date is before 2009-02-23, iteration
  • at each iteration add 7 * 24 * 3600 seconds (7 days a week, 24 hours a day, 3600 seconds per hour).

Note. I changed the format of your dates to use YYYY-MM-DD, not DD-MM-YYY; this is the format that is commonly used - so it's probably a good idea to use it to make sure strtotime is working correctly. (not sure if it will work with your format)

+5
source

This should do the trick without any cycles.

 $start = mktime(0, 0, 0, $start_month, $start_day, $start_year); $end = mktime(0, 0, 0, $end_month, $end_day, $end_year); $days = ($end - $start) / 86400; $sundays = $days / 7 // check if there are enough leftover days for one more sunday if((localtime($start)[6]+($days % 7) > 6) $sundays++; 
+2
source
  $sunday=0; for($i=1; $i<=date("t", strtotime("2012-09-01")); $i++) { if(date("l", strtotime("2012-09-".$i)) === 'Sunday') { $sunday++; } } echo "no of Sunday=".$sunday; 
+1
source

You can calculate how many weeks are between these two dates, there should be some kind of date management library in PHP, and then the number of Sundays will be the number of weeks, you still need to see if the first date is Sunday or not, and the last date is Sunday or not deal with the edges of a date range.

Some examples can be seen here .

0
source

I saw it somewhere here in SO, and I used it in my project. Failed to track the original post.

 // function to calculate number of given day within date range 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 your dates $start = mktime(0, 0, 0, 1, 16, 2010); $end = mktime(0, 0, 0, 1, 25, 2010); // display the count echo number_of_days(0, $start, $end); 
0
source

Source: https://habr.com/ru/post/1393556/


All Articles