Home >Backend Development >PHP Tutorial >How Can I Write a PHP Function to Check if a Date is a Weekend?
A common programming task involves checking if a given date is a weekend day, Saturday or Sunday. However, occasionally, problems arise when implementing this functionality.
Consider the following PHP function:
function isweekend($date){ $date = strtotime($date); $date = date("l", $date); $date = strtolower($date); echo $date; if($date == "saturday" || $date == "sunday") { return "true"; } else { return "false"; } }
When called with $isthisaweekend = isweekend('2011-01-01');, this function consistently returns "false." To resolve this issue and determine if a date is indeed a weekend, consider employing one of the following methods:
For PHP versions 5.1 and above:
function isWeekend($date) { return (date('N', strtotime($date)) >= 6); }
For earlier PHP versions:
function isWeekend($date) { $weekDay = date('w', strtotime($date)); return ($weekDay == 0 || $weekDay == 6); }
These improved functions accurately identify weekends by examining the day of the week (date('N')) or weekday (date('w')) properties of the date object.
The above is the detailed content of How Can I Write a PHP Function to Check if a Date is a Weekend?. For more information, please follow other related articles on the PHP Chinese website!