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

后端 未结 8 1375
情话喂你
情话喂你 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 04:20

    This really depends on how you define a week but I came up with this function that will give you the date for the nearest "monday" or "friday" (or any day for that matter):

    function closestDate($day){
    
        $day = ucfirst($day);
        if(date('l', time()) == $day)
            return date("Y-m-d", time());
        else if(abs(time()-strtotime('next '.$day)) < abs(time()-strtotime('last '.$day)))
            return date("Y-m-d", strtotime('next '.$day));
        else
            return date("Y-m-d", strtotime('last '.$day));
    
    }
    

    Input: a day of the week ("sunday", "Monday", etc.)

    Output: If I asked for the nearest "sunday" and today is:

    1. "Sunday": I will get today's date
    2. "Monday": I will get yesterday's date
    3. "Saturday: I will get tomorrow's date

    Hope this helps :)

    0 讨论(0)
  • 2020-12-01 04:21

    As the top answer suggests, using PHP's strtotime() function is the easiest way.

    However, instead of using if statements as he suggests, you could simply reset back to the previous Sunday and grab the dates you require from there.

    $monday = strtotime('next monday', strtotime('previous sunday'));
    $friday = strtotime('next friday', strtotime('previous sunday'));
    
    0 讨论(0)
提交回复
热议问题