Home  >  Article  >  Backend Development  >  PHP calculates the number of weeks in a year and the start and end dates of each week_PHP Tutorial

PHP calculates the number of weeks in a year and the start and end dates of each week_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:26:32871browse

The project needs to have a function to submit weekly reports, and needs to know the start date and end date of the specified weeks in order to handle other business. The following is a piece of code that uses PHP to get the start date and end date of each week of the year to share with you.

Copy code The code is as follows:

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)); //Get the date of the first week of the year
}
$year_mondy = date("Y-m-d", $startday); //Get the date of the first week of the year

$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() gets the week number of the first and last days of the year by passing in the parameter $year, calculates the date of the first week, and obtains the dates of the first and last days of each week through a loop. The final return is an array.
If you want to get the start date and end date of a specified week, such as the start date and end date of week 18 in 2011, the code is as follows:

Copy code The code is as follows:

$weeks = get_week(2011);
echo 'Start date of week 18:'.$weeks[18][0].'';
echo 'End date of week 18:'.$weeks[18][1];

Final output result:

Week 18 start date: 2011.05.02
Week 18 end date: 2011.05.08

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824689.htmlTechArticleThe project needs to have a function to submit weekly reports. It needs to know the start date and end date of the specified weeks for processing. Other business. The following is a paragraph to get each week of the year through PHP...
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