Checking if date is weekend PHP

Checking if date is weekend PHP

Asked on December 24, 2018 in PHP.
Add Comment


  • 3 Answer(s)

    This code for PHP >= 5.1 users,

    function isWeekend($date) {
        return (date('N', strtotime($date)) >= 6);
    }
    

    For others,

    function isWeekend($date) {
        $weekDay = date('w', strtotime($date));
        return ($weekDay == 0 || $weekDay == 6);
    }
    
    Answered on December 24, 2018.
    Add Comment

    In PHP 5.3 or higher we have another way to do this, that is to use the DateTime class.

    By using this way one can also specify the timezone.

    // For the current date
    function isTodayWeekend() {
        $currentDate = new DateTime("now", new DateTimeZone("Europe/Amsterdam"));
        return $currentDate->format('N') >= 6;
    }
    

    The DateTime::createFromFormat can be used to check a certain date string,

    function isWeekend($date) {
        $inputDate = DateTime::createFromFormat("d-m-Y", $date, new DateTimeZone("Europe/Amsterdam"));
        return $inputDate->format('N') >= 6;
    }
    

        The benefit of using this method, one can specify the timezone without changing the whole timezone in PHP. Because if it change it affects other scripts like wordpress and so on.

    Answered on December 24, 2018.
    Add Comment

    Use this code to get solution,

    function isweekend($year, $month, $day)
    {
        $time = mktime(0, 0, 0, $month, $day, $year);
        $weekday = date('w', $time);
        return ($weekday == 0 || $weekday == 6);
    }
    
    Answered on December 24, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.