w3resource

PHP Date Exercises : Check whether a date is a weekend or not

PHP date: Exercise-15 with Solution

Write a PHP script to check whether a date is a weekend or not.

Sample Solution:

PHP Code:

<?php
$dt='2011-01-04'; // Assigning the date '2011-01-04' to the variable $dt.
$dt1 = strtotime($dt); // Converting the date string to a Unix timestamp and storing it in $dt1.
$dt2 = date("l", $dt1); // Formatting the Unix timestamp $dt1 to retrieve the day of the week in full textual representation (e.g., 'Monday') and storing it in $dt2.
$dt3 = strtolower($dt2); // Converting the day of the week to lowercase and storing it in $dt3.

if (($dt3 == "saturday") || ($dt3 == "sunday")) { // Checking if the day is Saturday or Sunday.
    echo $dt3.' is weekend'."\n"; // Outputting that it's a weekend if the day is Saturday or Sunday.
} else {
    echo $dt3.' is not weekend'."\n"; // Outputting that it's not a weekend if the day is not Saturday or Sunday.
}
?>

Output:

tuesday is not weekend

Explanation:

In the exercise above,

  • $dt='2011-01-04';: Assigning the date '2011-01-04' to the variable '$dt'.
  • $dt1 = strtotime($dt);: Converting the date string stored in '$dt' to a Unix timestamp and storing it in the variable '$dt1'.
  • $dt2 = date("l", $dt1);: Formatting the Unix timestamp stored in '$dt1' to retrieve the day of the week in full textual representation (e.g., 'Monday') and storing it in the variable '$dt2'.
  • $dt3 = strtolower($dt2);: Converting the day of the week stored in '$dt2' to lowercase and storing it in the variable '$dt3'.
  • Checking if the day stored in '$dt3' is Saturday or Sunday using an if-else statement.
  • Outputting whether the day is a weekend day or not based on the result of the if-else condition.

Flowchart :

Flowchart: Check whether a date is a weekend or not

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to get the current date/time of 'Australia/Melbourne'.
Next: Write a PHP script to add/subtract the number of days from a particular date.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-date-exercise-15.php