phpweekend

Check if 2 given dates are a weekend using PHP


I have 2 dates like this YYYY-mm-dd and I would like to check if these 2 dates are a weekend.

I have this code but it only tests 1 date and I don't know how to adapt it; I need to add a $date_end.

$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
    echo "true";
} else {
    echo "false";
}

Solution

  • You can use shorter code to check for weekend => date('N', strtotime($date)) >= 6. So, to check for 2 dates — and not just 1 — use a function to keep your code simple and clean:

    $date1 = '2011-01-01' ;
    $date2 = '2017-05-26';
    
    if ( check_if_weekend($date1) && check_if_weekend($date2) ) {
        echo 'yes. both are weekends' ;
    
    } else if ( check_if_weekend($date1) || check_if_weekend($date2) ) {
        echo 'no. only one date is a weekend.' ;
    
    } else {
        echo 'no. neither are weekends.' ;
    }
    
    function check_if_weekend($date) {
        return (date('N', strtotime($date)) >= 6);
    }
    

    Using your existing code, which is slightly longer, following is how you would check for 2 dates:

    $date1 = '2011-01-01' ;
    $date2 = '2017-05-27';
    
    if ( check_if_weekend_long($date1) && check_if_weekend_long($date2) ) {
        echo 'yes. both are weekends' ;
    
    } else if ( check_if_weekend_long($date1) || check_if_weekend_long($date2) ) {
        echo 'no. only one date is a weekend.' ;
    
    } else {
        echo 'no. neither are weekends.' ;
    }
    
    function check_if_weekend_long($date_str) {
        $timestamp = strtotime($date_str);
        $weekday= date("l", $timestamp );
        $normalized_weekday = strtolower($weekday);
        //echo $normalized_weekday ;
        if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
            return true;
        } else {
            return false;
        }
    }