-3

I'm new to php and looking for snippet of week number in a month and what is the current week number in today's month. Thank you for those who will answer

2 Answers2

1

I am using this.

<?php

function weeks($month, $year){
    $firstday = date("w", mktime(0, 0, 0, $month, 1, $year)); 
    $lastday = date("t", mktime(0, 0, 0, $month, 1, $year)); 
    $count_weeks = 1 + ceil(($lastday-7+$firstday)/7);
    return $count_weeks;
}

echo weeks(11,2016)."<br/>";

?>

Result:

5

DEMO

https://eval.in/683361

Irvin
  • 830
  • 5
  • 13
1

Using a Simple DateTime() Class as shown below could do. Just change the Value of the $anyDate Variable to suit whatever Date you prefer and you are good to go. The $weekNum will be the Week Number corresponding to the provided Date ($anyDate) Quick-Test Here.

<?php

    $anyDate    = "2016-11-22";
    $objDT      = new DateTime($anyDate);
    $weekNum    = $objDT->format('W');     //<== RETURNS THE WEEK NUMBER OF $anyDate

    var_dump($weekNum);                    //<== YIELDS:: string '47' (length=2)    

On the other hand, if you are interested in the Week of the Month in the Context of the current Date (that is, as in: the 3rd Week of November or something similar); you could modify your code as shown below. Quick Test Here.

<?php
    $firstDayOfMonth    = "2016-11-01";
    $currentDate        = "2016-11-22";
    $dtCurrent          = new \DateTime($currentDate);
    $dtFirstOfMonth     = new \DateTime($firstDayOfMonth);
    $numWeeks           = 1 + ( intval($dtCurrent->format("W")) - 
                                intval($dtFirstOfMonth->format("W")));

    var_dump($numWeeks);             //<== YIELDS:: int 4    
                                     //<== 22ND IS THE 4TH WEEK IN THE MONTH OF NOVEMBER   

                                     //<== ONE CAN EQUALLY READ IT THUS: 22ND FALLS INTO 
                                     //<== WEEK NR. 4 IN THE MONTH OF NOVEMBER   

Cheers and Good-Luck

Poiz
  • 7,611
  • 2
  • 15
  • 17