Home > Backend Development > PHP Tutorial > How Can I Efficiently Determine if a Given Date is a Weekend in PHP?

How Can I Efficiently Determine if a Given Date is a Weekend in PHP?

Mary-Kate Olsen
Release: 2024-11-26 08:17:09
Original
792 people have browsed it

How Can I Efficiently Determine if a Given Date is a Weekend in PHP?

Checking if a Date is a Weekend in PHP

The provided PHP function, isweekend(), appears to always return false due to an oversight. Here's a corrected version:

function isWeekend($date) {
    $dayOfWeek = strtolower(date("l", strtotime($date)));
    if ($dayOfWeek == "saturday" || $dayOfWeek == "sunday") {
        return true;
    } else {
        return false;
    }
}
Copy after login

For PHP versions 5.1 and above, a more concise solution exists:

function isWeekend($date) {
    return (date('N', strtotime($date)) >= 6);
}
Copy after login

In both cases, the function checks the weekday and returns true if it falls on a Saturday or Sunday (Saturday has a value of 6 and Sunday 7 when using the date('N') function).

To use the corrected isWeekend() function:

$isThisAWeekend = isWeekend('2011-01-01');
Copy after login

This will correctly indicate whether the input date is a weekend.

The above is the detailed content of How Can I Efficiently Determine if a Given Date is a Weekend in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template