How to Determine Weekend Status of a Date in PHP
This question arises when working with functions that aim to identify if a given date falls on a weekend. One such function, provided by the user, returns only false values despite seemingly valid parameters.
The Issue
The provided function, isweekend(), performs the following steps:
However, it returns "false" regardless of the input date.
The Solution
There are two alternative solutions to accurately determine the weekend status of a date in PHP:
For PHP >= 5.1:
function isWeekend($date) { return (date('N', strtotime($date)) >= 6); }
This solution uses date('N') to return the day of the week as an integer, where 1 represents Monday and 7 represents Sunday. It then checks if this integer is greater than or equal to 6, indicating a weekend.
For PHP < 5.1:
function isWeekend($date) { $weekDay = date('w', strtotime($date)); return ($weekDay == 0 || $weekDay == 6); }
This solution uses date('w') to return the day of the week as an integer, where 0 represents Sunday and 6 represents Saturday. It then checks if the integer is either 0 or 6 to determine if it's a weekend.
The above is the detailed content of How Can I Reliably Determine if a Given Date is a Weekend in PHP?. For more information, please follow other related articles on the PHP Chinese website!