Get date for monday and friday for the current week (PHP)

后端 未结 8 1405
情话喂你
情话喂你 2020-12-01 03:46

How can I get the date for monday and friday for the current week?

I have the following code, but it fails if current day is sunday or saturday.

$cu         


        
8条回答
  •  伪装坚强ぢ
    2020-12-01 03:57

    I was looking for a similar thing, except I wanted any Monday, not just this week. This is what I came up with:

    function getSunday(DateTime $date){
        $outdate = clone($date);
        $day = $date->format("w");  // get the weekday (sunday is 0)
        $outdate->sub(new DateInterval("P".$day."D")); // subtracting the weekday from the date always gives Sunday 
        return $outdate;
    }
    

    It accepts an arbitrary date and gives the Sunday. Then you can easily add back days to get Monday through Saturday.

提交回复
热议问题