Get week number (in the year) from a date PHP

前端 未结 17 2015
星月不相逢
星月不相逢 2020-11-27 14:54

I want to take a date and work out its week number.

So far, I have the following. It is returning 24 when it should be 42.



        
17条回答
  •  离开以前
    2020-11-27 15:34

    The most of the above given examples create a problem when a year has 53 weeks (like 2020). So every fourth year you will experience a week difference. This code does not:

    $thisYear = "2020";
    $thisDate = "2020-04-24"; //or any other custom date
    $weeknr = date("W", strtotime($thisDate)); //when you want the weeknumber of a specific week, or just enter the weeknumber yourself
    
    $tempDatum = new DateTime();
    $tempDatum->setISODate($thisYear, $weeknr);
    $tempDatum_start = $tempDatum->format('Y-m-d');
    $tempDatum->setISODate($thisYear, $weeknr, 7);
    $tempDatum_end = $tempDatum->format('Y-m-d');
    
    echo $tempDatum_start //will output the date of monday
    echo $tempDatum_end // will output the date of sunday
    

提交回复
热议问题