Month by week of the year?

前端 未结 4 487
感动是毒
感动是毒 2021-01-22 22:30

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

相关标签:
4条回答
  • 2021-01-22 22:42

    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"));
    
    0 讨论(0)
  • 2021-01-22 22:43

    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 讨论(0)
  • 2021-01-22 22:45

    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)
    0 讨论(0)
  • 2021-01-22 23:04
    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).

    0 讨论(0)
提交回复
热议问题