Get all Work Days in a Week for a given date

后端 未结 5 1756
萌比男神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:28

    This seems to work:

    $d = date('N', strtotime('2011/06/01'));
    // here N means ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
    $week = array();
    for($i = 1; $i < $d; ++$i){
        $dateTime = new DateTime('2011/06/01');
        for($j = 0; $j < $i; ++$j){
            $dateTime->modify('-1 day');
        }   
        $week[] = $dateTime;
    }
    $week[] = new DateTime('2011/06/01');
    for($i = $d+1; $i <= 7; ++$i){
        $dateTime = new DateTime('2011/06/01');
        for($j = 0; $j < $i - $d; ++$j){
            $dateTime->modify('+1 day');
        }   
        $week[] = $dateTime;
    }
    sort($week);
    
    foreach($week as $day){
        echo $day->format('Y-m-d H:i:s'), '
    '; }

提交回复
热议问题