1

I have a date, I want to get the week number of that month, how can i do that?

I tried:

$time = '2016/05/21';
echo date("w", strtotime($time));

I also tried with W but it is for week of year, but in my case, i need for the month.

Current Result: 6.

Desire Result: 4.

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
  • lower-case "w" is the day of the week, not the week number in the month. That's stated clearly in the [documentation](https://secure.php.net/manual/en/function.date.php). You probably meant upper-case "W" which is the ISO week number, not the week number in the month. When you say, "week number of that month", what is week "1" - if first day is Saturday, is the 2nd of that month week 2 or 1? Some people count starting on Monday, some Sunday, some based on ISO week number, etc.... you need to clarify what the first week is. – cegfault May 22 '16 at 03:54
  • In my case, "Sunday" is the starting day. –  May 22 '16 at 03:56

2 Answers2

4

Try 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;
  }

You can see it here here

You must execute as

$datee = "2016/08/10";
$datee = strtotime( str_replace("/", "-", $datee));
echo weekOfMonth($datee);
Community
  • 1
  • 1
hemnath mouli
  • 2,617
  • 2
  • 17
  • 35
0

I found the same solution of it in another PHP get number of week for month, Please take a look.

function getWeeks($date, $rollover)
{
    $cut = substr($date, 0, 8);
    $daylen = 86400;

    $timestamp = strtotime($date);
    $first = strtotime($cut . "00");
    $elapsed = ($timestamp - $first) / $daylen;

    $weeks = 1;

    for ($i = 1; $i <= $elapsed; $i++)
    {
        $dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
        $daytimestamp = strtotime($dayfind);

        $day = strtolower(date("l", $daytimestamp));

        if($day == strtolower($rollover))  $weeks ++;
    }

    return $weeks;
}

$time = '2016/05/21';
echo getWeeks($time, 'Sunday'); //4
Community
  • 1
  • 1
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42