Dave Dave - 2 months ago 6
MySQL Question

Determine Week number from a date(Month) using PHP

I will like an assistance to get the determine if a particular date in a week falls into week1, week2 week3, or week 5 of that month. This code below returns 0-7 starting from mondaythrough saturday, but that is not what i wanted, rather i want to be able to determine e.g today is 19/09/2016, which falls into week3 of this Month. I need assistance on this please.

function getWeekday($date){
return date('w',strtotime($date));
}

Answer

All you need is

ceil(date('d')/7);

So your function will look like

function getWeekday($date){
  return ceil(date('d',strtotime($date))/7);
}

Demo

Even though requirement is a little strange. Week of the month is not a well defined thing but according to your comments on various answers all you need is to see week 1 if the date is within 1st 7 days of the month. 2 for next 7, 3 for next 7, 4 for next 7 and 5 for the leftovers.

Output

D   W
1   1
2   1
3   1
4   1
5   1
6   1
7   1
8   2
9   2
10  2
11  2
12  2
13  2
14  2
15  3
16  3
17  3
18  3
19  3
20  3
21  3
22  4
23  4
24  4
25  4
26  4
27  4
28  4
29  5
30  5
31  5

Old answer

Simple! you need a capital W, not a lowercase one.

W

ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)

return date('W',strtotime($date));

The lowercase one - which you are using - is

Numeric representation of the day of the week

Manual