Home  >  Article  >  Backend Development  >  How can I extract the days of the week within a given week number in PHP, starting with Monday?

How can I extract the days of the week within a given week number in PHP, starting with Monday?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 06:10:30373browse

How can I extract the days of the week within a given week number in PHP, starting with Monday?

Calculating Days of the Week Given a Week Number

This problem aims to extract the days of the week within a given week number, specifically commencing with Monday.

PHP Solution

The following PHP code can be utilized to achieve this calculation:

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

This script produces the following output for week 40:

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

Alternative PHP Solution for Extracting Dates within a Week

Below is an adapted solution that operates slightly differently:

<code class="php">function week_from_monday($date) {
    list($day, $month, $year) = explode('-', $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;
    }

    $monday = mktime('0', '0', '0', $month, $day - $numDaysToMon, $year);

    $seconds_in_a_day = 86400;

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

    return $dates;
}

This function accepts a date string in the format 'DD-MM-YYYY' and converts it into an array of dates representing the days in the week starting from Monday. For instance, using the date '07-10-2008' yields the following array:

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 can I extract the days of the week within a given week number in PHP, starting with Monday?. 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