Get week number in month from date in PHP?

前端 未结 14 2225
说谎
说谎 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

    $date = new DateTime('first Monday of this month');
    $thisMonth = $date->format('m');
    $mondays_arr = [];
    
    // Get all the Mondays in the current month and store in array
    while ($date->format('m') === $thisMonth) {
        //echo $date->format('Y-m-d'), "\n";
        $mondays_arr[] = $date->format('d');
        $date->modify('next Monday');
    }
    
    // Get the day of the week (1-7 from monday to sunday)
    $day_of_week = date('N') - 1;
    
    // Get the day of month (1 to 31) 
    $current_week_monday_date = date('j') - $day_of_week;
    
    /*$day_of_week = date('N',mktime(0, 0, 0, 2, 11, 2020)) - 1;
    $current_week_monday_date = date('j',mktime(0, 0, 0, 2, 11, 2020)) - $day_of_week;*/
    
    $week_no = array_search($current_week_monday_date,$mondays_arr) + 1;
    echo "Week No: ". $week_no;
    

提交回复
热议问题