Get week number in month from date in PHP?

前端 未结 14 2161
说谎
说谎 2020-11-28 11:15

I have an array of random dates (not coming from MySQL). I need to group them by the week as Week1, Week2, and so on upto Week5.

What I have is this:



        
14条回答
  •  攒了一身酷
    2020-11-28 11:45

    // self::DAYS_IN_WEEK = 7;
    function getWeeksNumberOfMonth(): int
    {
        $currentDate            = new \DateTime();
        $dayNumberInMonth       = (int) $currentDate->format('j');
        $dayNumberInWeek        = (int) $currentDate->format('N');
        $dayNumberToLastSunday  = $dayNumberInMonth - $dayNumberInWeek;
        $daysCountInFirstWeek   = $dayNumberToLastSunday % self::DAYS_IN_WEEK;
        $weeksCountToLastSunday = ($dayNumberToLastSunday - $daysCountInFirstWeek) / self::DAYS_IN_WEEK;
    
        $weeks = [];
        array_push($weeks, $daysCountInFirstWeek);
        for ($i = 0; $i < $weeksCountToLastSunday; $i++) {
            array_push($weeks, self::DAYS_IN_WEEK);
        }
        array_push($weeks, $dayNumberInWeek);
    
        if (array_sum($weeks) !== $dayNumberInMonth) {
            throw new Exception('Logic is not valid');
        }
    
        return count($weeks);
    }
    

    Short variant:

    (int) (new \DateTime())->format('W') - (int) (new \DateTime('first day of this month'))->format('W') + 1;
    

提交回复
热议问题