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
Mary-Kate OlsenOriginal
2024-11-26 08:17:09845browse

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;
    }
}

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

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

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');

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!

Statement:
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