简体   繁体   中英

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";
}

A couple of hints:

  • date('N') gives you normalised week day you can test against (no need to use localised strings)
  • Wrap it all in a custom function and you're done

You can use the strtotime(); and date() functions to get the day of the date, and then check if is sat o sun

 function check_if_weekend($date){
    $timestamp = strtotime($date);
    $day = date('D', $timestamp);
    if(in_array($day, array('sun', 'sat'))
       return true;
    else return false;
    }

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;
    }
}

Merging multiple answers into one and giving a bit extra, you'd come to the following:

function isWeekend($date) {
    return (new DateTime($date))->format("N") > 5 ? true : false; 
}

Or the long way:

function isWeekend($date) {
    if ((new DateTime($date))->format("N") > 5) {
        return true;
    } 
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM