Asif Hussain Asif Hussain - 7 months ago 171
PHP Question

Get week number in month from date in PHP?

I have an array of random dates (not coming from MySQL). I need to group them by the week as Week1, Week2, and so on upto Week5.

What I have is this:

$dates = array('2015-09-01','2015-09-05','2015-09-06','2015-09-15','2015-09-17');


What I need is a function to get the week number of the month by providing the date.

I know that I can get the weeknumber by doing
date('W',strtotime('2015-09-01'));

but this week number is the number between year (1-52) but I need the week number of the month only, e.g. in Sep 2015 there are 5 weeks:


  • Week1 = 1st to 5th

  • Week2 = 6th to 12th

  • Week3 = 13th to 19th

  • Week4 = 20th to 26th

  • Week5 = 27th to 30th



I should be able to get the week Week1 by just providing the date
e.g.

$weekNumber = getWeekNumber('2015-09-01') //output 1;
$weekNumber = getWeekNumber('2015-09-17') //output 3;

Answer

I think this relationship should be true (?) and come in handy:

Week of the month = Week of the year - Week of the year of first day of month + 1

Implemented in PHP you get this:

function weekOfMonth($date) {
    //Get the first day of the month.
    $firstOfMonth = strtotime(date("Y-m-01", $date));
    //Apply above formula.
    return intval(date("W", $date)) - intval(date("W", $firstOfMonth)) + 1;
}

To get weeks that starts with sunday, simply replace both date("W", ...) with strftime("%U", ...).