PHP: Check if a date falls on the weekend.

In this PHP tutorial, we are going to show you how to check if a given date falls on the weekend or not.

This is particularly useful if you are building a PHP script that displays the “open” or “closed” status of a service or business.

Take a look at the following example:

//Date in YYYY-MM-DD format.
$date = '2016-08-21';

//Set this to FALSE until proven otherwise.
$weekendDay = false;

//Get the day that this particular date falls on.
$day = date("D", strtotime($date));

//Check to see if it is equal to Sat or Sun.
if($day == 'Sat' || $day == 'Sun'){
    //Set our $weekendDay variable to TRUE.
    $weekendDay = true;
}

//Output for testing purposes.
if($weekendDay){
    echo $date . ' falls on the weekend.';
} else{
    echo $date . ' falls on a weekday.';
}

An explanation of this code:

  1. In this example, our date is “2016-08-21”. “2016-08-21” was a Sunday, which means that the rest of our code should prove that it fell on the weekend.
  2. We set ourĀ $weekendDay variable to FALSE by default.
  3. We are able to determine the day of the week by using PHP’s date function and the “D” format character. The “D” format character returns a three-letter textual representation of the day. For example, it might return “Mon”, “Thu”, or “Sat”.
  4. After that, we use a simple IF statement to check if the day is equal to Sat or Sun. If it is equal to Sat or Sun, then we set our $weekendDay variable to TRUE.
  5. Finally, we print the result onto the page.

As you can imagine, this is very useful if you are displaying opening times for a local business.

To test this script, feel free to change the date around.