tradebel123
tradebel123

Reputation: 435

How to find week number of a day in a month using php

hai i found this PHP get number of week for month quiet helpful but it makes some error on all months start on Sundays for example "2013-09-01" gives week number as 2 (actually its '1').. any one got some idea?? please share thanks in advance.....

Upvotes: 0

Views: 3586

Answers (3)

voghDev
voghDev

Reputation: 5791

This utility function returns the week of the month for a specific day. Needs two args: the wanted day, and the first day of the same month

class WeekCalculator
{    
    public static function getWeekOfMonth($date, $firstDayOfMonth) {    
        $w1 = date("W", $firstDayOfMonth->getTimestamp());
        $w2 = date("W", $date->getTimestamp());

        $weekNum = $w2 - $w1 + 1;
        return $weekNum;
    }
}

Example usage

WeekCalculator::getWeekOfMonth(new \DateTime('2016-8-8'), new \DateTime('2016-8-1'));

Returns 2 (second week of August 2016)

Upvotes: 1

Add strtotime function to it.. Works fine.. date("W",strtotime("2013-09-01"));

Upvotes: 1

Ripa Saha
Ripa Saha

Reputation: 2540

use date("W","2013-09-01");.it will return week number as 01.

Upvotes: 3

Related Questions