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
Asked
Active
Viewed 6,802 times
-3
-
8Check this http://stackoverflow.com/questions/5853380/php-get-number-of-week-for-month – Melchizedek Nov 23 '16 at 02:55
2 Answers
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

Irvin
- 830
- 5
- 13
-
if I wanted to start the first week as the first sunday of the month? – Earvin Nill Castillo Nov 23 '16 at 05:23
-
Like what? The code is fine with Sunday as the first day of the week. The same as for month. – Irvin Nov 23 '16 at 05:28
-
since nov 1 is tuesday, therefore the first sunday of month must be nov 6 – Earvin Nill Castillo Nov 23 '16 at 05:33
-
I have been looking around for this and I believe this is the simplest working code I could find!!! – Umar Niazi Dec 21 '22 at 02:12
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
-
I think what OP wanted is to count the `number of weeks` in the current month not the `week number of the year`. – Irvin Nov 23 '16 at 03:26
-
Ahhhhaaa..... You might be right @Irvin.... Perhaps, one could also add that as an alternative... but ***Thanks, anyways for pointing out the probability...* ;-)** – Poiz Nov 23 '16 at 03:31
-
-
$date = date('Y-m-d'); $newdate = strtotime ( 'W', strtotime ( $date ) ) ; $newdate = date ( 'W' , $newdate ); echo $newdate; – Earvin Nill Castillo Nov 23 '16 at 05:20