Get the number of weeks passing month and year php

I know that I have a question like this, but I don’t know if I am blind or what, but I can’t find an answer that fits my question, so here it is.

I have 2 combobox - month and year , I need a function that brings me the week number from the month and year that I selected.

example:

i select the date 02/2012 (m / yyyy), and the combo will display the weeks that belong to the month that I choose. ( weeks from a year ).

weeks:

5, 6, 7, 8, 9


My main goal is to pass the week number to another function in order to get the day that this week has, for example, returning this function:

 $week_number = 40; $year = 2012; if($week_number < 10){ $week_number = "0".$week_number; } for($day=1; $day<=7; $day++) { echo date('m/d/Y', strtotime($year."W".$week_number.$day))."<br/>"; } 

I don’t know if I can make my clear, but, any question of my guest.

Thanks.


summary:

52 weeks a year

if I select month 2, the function should return 5, 6, 7, 8, 9 .

+4
source share
2 answers

I think you should be able to work with this?

 $month = "2"; $year = "2012"; $beg = (int) date('W', strtotime("first thursday of $year-$month")); $end = (int) date('W', strtotime("last thursday of $year-$month")); print(join(', ', range($beg, $end))); 

OUTPUT

 5, 6, 7, 8 

Note

This code was faulty and produced incorrect results until it was fixed on August 27, 2014.

The period of time during which a week belongs is determined by where most (four or more) of its days are. This is easiest to determine by checking where its Thursday falls. So, the first and last weeks of the month are the first and last Thursdays.

+12
source

First enter the timestamp for the 1st of the month / year. And based on this, get the week number on the first day.

Like this:

 $year = "2012"; $mon = "02"; $tm = strtotime("$year-$mon-01"); # Substitue year and month $first_week_num = date("W", $tm); # Got the week number 

And then do the same on the last day of the month. To do this, you can simply add 1 to the month (you need to make logic if in the month of 12, where you need to add 1 to the year). And then subtract 86400 (number of seconds per day). Thus, you will receive the last day of the month and do not bother to find out how many days are in this month.

 if($mon == 12) $year++; else $mon++; $tm = strtotime("$year-$mon-01") - 86400; $last_week_num = date("W", $tm); 

And all the weeks from the first week to the last week is what you need:

 for($i=$first_week_num; $i <= $last_week_num; $i++) print $i; 
+2
source

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


All Articles