Ricardo Binns
Ricardo Binns

Reputation: 3246

get number of weeks passing month and year php

i know that have alot of question like this one, but i dont know if i'm blind or what, but i cant find a answer that qualify to my question, so here it go.

i have 2 combobox - month and year, i need a function that bring to me the week number's from the month and year that i selected.

example:

i select the date 02/2012 (m/yyyy), and the combo will bring the weeks that belongs to the month that i select. ( weeks from the year ).

weeks:

5, 6, 7, 8, 9


my main objective is to pass to another function the week number to get the day's that this week have, like the returns of 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/>";
}

dont know if i make my self clear,but, any question by my guest.

Thanks.


resume:

52 weeks in a year

if i choose the month 2, the function should return 5, 6, 7, 8, 9.

Upvotes: 4

Views: 6983

Answers (2)

Borodin
Borodin

Reputation: 126732

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 27-Aug-2014.

The time period that a week belongs to is determined by where most (four or more) of its days are. That is most simply determined by checking where its Thursday falls. So the first and last weeks of a month are the ones containing its first and last Thursdays.

Upvotes: 12

rsmoorthy
rsmoorthy

Reputation: 2372

First, get the timestamp for the 1st day of the month/year. And based on that, get the week number of 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 for the last day of the month. For that, you can simply add 1 to the month (you need to do the logic, if the month is 12 - where you need to add 1 to the year). And then subtract 86400 (number of seconds per day). This way you will get the last day of the month and not bother about finding how many days in that 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;

Upvotes: 2

Related Questions