Get all Work Days in a Week for a given date

后端 未结 5 1753
萌比男神i
萌比男神i 2020-12-06 14:58

So I have one date as a string:

2011/06/01

I need to get the 5 DateTime objects from it that correspond to the five weekdays (Monday to Fri

5条回答
  •  猫巷女王i
    2020-12-06 15:38

    I've done this for 1 complete week. I created one function which return the list of all days in a week. I let you the code below

    public function daysOfWeekXML($day)
    {
        // Give number of day in the week
        $day_number = date('N', strtotime($day));
    
        $day_week_futur = [];
        $day_week_past = [];
    
        // Retrieve future days in the week
        for ($i = $day_number; $i <= 7; $i++) {
            $next_day = strtotime('+' . $i - $day_number . ' day', strtotime($day));
            array_push($day_week_futur, date('Y-m-d', $next_day));
        }
    
        // Retrieve days past in the week
        for ($day_number; $day_number > 1; $day_number--) {
            $previous_day = strtotime('-' . ($day_number - 1) . ' day', strtotime($day));
            array_push($day_week_past, date('Y-m-d', $previous_day));
        }
        // Concatenate all days in the week in array
        return array_merge($day_week_past, $day_week_futur);
    }
    

提交回复
热议问题