PHP Calculates the number of weeks in a year and the start and end dates of each week

  • 2021-07-06 10:22:16
  • OfStack

Project need to do a weekly report to submit the function, need to know the specified weeks of the start date and end date, in order to deal with other business. The following is a section of PHP to get the start date and end date of each week in a year of code, to share with you.


function get_week($year) {
    $year_start = $year . "-01-01";
    $year_end = $year . "-12-31";
    $startday = strtotime($year_start);
    if (intval(date('N', $startday)) != '1') {
        $startday = strtotime("next monday", strtotime($year_start)); // Acquisition year 1 Date of the week
    }
    $year_mondy = date("Y-m-d", $startday); // Acquisition year 1 Date of the week
 
    $endday = strtotime($year_end);
    if (intval(date('W', $endday)) == '7') {
        $endday = strtotime("last sunday", strtotime($year_end));
    }
 
    $num = intval(date('W', $endday));
    for ($i = 1; $i <= $num; $i++) {
        $j = $i -1;
        $start_date = date("Y-m-d", strtotime("$year_mondy $j week "));
 
        $end_day = date("Y-m-d", strtotime("$start_date +6 day"));
 
        $week_array[$i] = array (
            str_replace("-",
            ".",
            $start_date
        ), str_replace("-", ".", $end_day));
    }
    return $week_array;
}

The function get_week () obtains the number of weeks of the first and last days of the current year by passing in the parameter $year year, calculates the date of the first week, and loops the dates of the first and last days of every week. The last return is an array.
To get the start and end dates for the specified number of weeks, such as the start and end dates for the 18th week of 2011, the code is as follows:


$weeks = get_week(2011);
echo ' No. 1 18 Week start date: '.$weeks[18][0].'';
echo ' No. 1 18 Week end date: '.$weeks[18][1];

Final output:

Week 18 Start Date: May 21, 2011
End date of week 18: May 8, 2011


Related articles: