PHP: Check if date falls on weekend.

This is a short PHP tutorial on how to determine if a given date falls on the weekend or not. This is particularly useful for PHP scripts that automatically display the “open” / “closed” status of a business or service.

Take a look at the following PHP code:

<?php

//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.';
}

Explanation:

  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 what day our date fell on by using PHP’s date function and the “D” format character. The “D” format character returns a three-letter textual representation of the day. i.e. “Mon”, “Tue”, “Fri”, “Sat” and “Sun”.
  4. We use a simple OR statement to check if the day is equal to Sat or Sun. If it is equal to Sat or Sun, we set our $weekendDay variable to TRUE.
  5. Finally, we print the result out onto the web page.

To test the above script, feel free to change the date around!