Month by week of the year?

前端 未结 4 494
感动是毒
感动是毒 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: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)

提交回复
热议问题