Cobra_Fast
Cobra_Fast

Reputation: 16061

Month by week of the year?

I'm trying to get the number of the month of the year by the number of a week of the year and the year. So for example week 1 is in january and returns 1, week 6 is in february so I want 2.

I tried to go with date_parse_from_format('W/Y') but had no success (it's giving me errors).

Is there any way to go with date_parse_from_format() or is there another way?

Upvotes: 2

Views: 2786

Answers (4)

Onema
Onema

Reputation: 7582

Using PHP DateTime objects (which is the preferred way of dealing with dates see links below for more info) you can accomplish it this way:

$dateTime = new \DateTime();
$dateTime->setISODate($year,$week);
$month = $dateTime->format('n');

Note that the following will not work as week "W" is not a supported format:

$month = \DateTime::createFromFormat("W/Y ", "1/2015")->format('n');

The format used by this method is the same supported by the function you where trying to use date_parse_from_format, hence the errors.

Upvotes: 2

Sara.G
Sara.G

Reputation: 21

Just wanted to add a note for the first answer, the week number should be 01-09 for Weeks 1 through 9 (it will always give month 1 if you don't add the leading zero)

date("m",strtotime("2011-W06-1"));

Upvotes: 2

RobertPitt
RobertPitt

Reputation: 57268

Something like this will do, this is also tested and works:

function getMonthByNumber($number,$year)
{
    return date("F",strtotime('+ '.$number.' weeks', mktime(0,0,0,1,1,$year,-1)));
}

echo getMonthByNumber(27,2011);

Hope this helps

Upvotes: 1

ADW
ADW

Reputation: 4080

print date("m",strtotime("2011-W6-1"));

(noting that in 2011, January has six weeks so week 6 (by some definitions) is in month 1).

Upvotes: 6

Related Questions