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

后端 未结 8 1417
情话喂你
情话喂你 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:58

    This question needs a DateTime answer:-

    /**
     * @param String $day
     * @return DateTime
     */
    function getDay($day)
    {
        $days = ['Monday' => 1, 'Tuesday' => 2, 'Wednesday' => 3, 'Thursday' => 4, 'Friday' => 5, 'Saturday' => 6, 'Sunday' => 7];
    
        $today = new \DateTime();
        $today->setISODate((int)$today->format('o'), (int)$today->format('W'), $days[ucfirst($day)]);
        return $today;
    }
    

    Usage:

    var_dump(getDay('Monday')->format('l dS F Y'));
    var_dump(getDay('Friday')->format('l dS F Y'));
    

    Output:

    string 'Monday 30th September 2013' (length=26)
    string 'Friday 04th October 2013' (length=24)
    

    See it working

提交回复
热议问题