PHP: Week starts on Monday, but “monday this week” on a Sunday gets Monday next week

后端 未结 10 1457
误落风尘
误落风尘 2020-12-09 14:43

Here\'s a summary of the issue: On Sundays, strtotime(\'this week\') returns the start of next week.

In PHP, the week seems to start on Monday. But, on

10条回答
  •  有刺的猬
    2020-12-09 15:18

    This is for thos looking for a friendly solution that works with any day.

    function getWeekStart($week_start_day = "Monday") {
        $week_days = array("Sunday"=>0,"Monday"=>1,"Tuesday"=>2,"Wednesday"=>3,"Thursday"=>4,"Friday"=>5,"Saturday"=>6,);
    
        if(!isset($week_days[$week_start_day])) {
            return false;
        } else {
            $start_day = $week_days[$week_start_day];
    
            $today = date("w");
            $one_day = (60 * 60 * 24);
    
            if($today < $start_day) {
                $days_difference = 7 - ($start_day - $today);
            } else {
                $days_difference = ($today - $start_day);
            }
    
            $week_starts = strtotime(date("Y-m-d 00:00:00")) - ($one_day * $days_difference);
    
            return $week_starts;
        }
    }
    
    //Test: If today is Monday, it will return today's date
    echo date("Y-m-d H:i:s", getWeekStart("Monday"));
    

提交回复
热议问题