开发者

Month by week of the year?

开发者 https://www.devze.com 2023-03-08 12:07 出处:网络
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.

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 w开发者_如何学Pythoneek 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?


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).


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"));


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.

  • Why PHP DateTime Rocks
  • DateTime class vs. native PHP date-functions
  • strtotime notes
  • PHP/Architect's Guide to Date and Time Programming (Chapter 2)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消