Home  >  Article  >  Backend Development  >  How to Calculate the Days of a Week in PHP Given a Week Number or a Specific Date?

How to Calculate the Days of a Week in PHP Given a Week Number or a Specific Date?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 01:41:30106browse

How to Calculate the Days of a Week in PHP Given a Week Number or a Specific Date?

Calculating Days of a Week

When given a week number, such as obtained from date -u %W, we might need to calculate the days within that week, starting from Monday. This allows us to generate a specific list of dates within that week.

PHP Implementation

In PHP, we can utilize a loop to generate the dates:

<code class="php">$week_number = 40;
$year = 2008;
for ($day = 1; $day <= 7; $day++) {
    echo date('m/d/Y', strtotime($year . "W" . $week_number . $day)) . "\n";
}

Output:

10/06/2008
10/07/2008
10/08/2008
10/09/2008
10/10/2008
10/11/2008
10/12/2008

Obtaining Dates from a Given Date

An alternative approach is to obtain a specific week's dates given a specific day. For instance, to get the dates of the week containing October 7th, 2008:

<code class="php">function week_from_monday($date) {
    // Assuming $date is in format DD-MM-YYYY
    list($day, $month, $year) = explode("-", $date);

    // Get the weekday of the given date
    $wkday = date('l', mktime(0, 0, 0, $month, $day, $year));

    switch ($wkday) {
        case 'Monday': $numDaysToMon = 0; break;
        case 'Tuesday': $numDaysToMon = 1; break;
        case 'Wednesday': $numDaysToMon = 2; break;
        case 'Thursday': $numDaysToMon = 3; break;
        case 'Friday': $numDaysToMon = 4; break;
        case 'Saturday': $numDaysToMon = 5; break;
        case 'Sunday': $numDaysToMon = 6; break;
    }

    // Timestamp of the Monday for that week
    $monday = mktime(0, 0, 0, $month, $day - $numDaysToMon, $year);

    $seconds_in_a_day = 86400;

    // Get date for 7 days from Monday (inclusive)
    for ($i = 0; $i < 7; $i++) {
        $dates[$i] = date('Y-m-d', $monday + ($seconds_in_a_day * $i));
    }

    return $dates;
}

Output:

Array
(
    [0] => 2008-10-06
    [1] => 2008-10-07
    [2] => 2008-10-08
    [3] => 2008-10-09
    [4] => 2008-10-10
    [5] => 2008-10-11
    [6] => 2008-10-12
)</code>

The above is the detailed content of How to Calculate the Days of a Week in PHP Given a Week Number or a Specific Date?. 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