Home > Article > Backend Development > php get all dates between start date and end date
Due to project requirements, it is necessary to obtain data within a specified date range and process it on a daily basis.
For example, it is necessary to process the data of each day in the date range from 2016-06-01 to 2016-06-05. First, you need to obtain the date of each day in this date range, and then perform processing in a loop.
<?php$date = array('2016-06-01','2016-06-02','2016-06-03','2016-06-04','2016-06-05');foreach($date as $d){ // 执行处理}?>
If the date range spans a large period (2015-09-01 to 2016-06-30), and there are situations where it spans years and months (leap months), manually creating the date array is too time-consuming and unreasonable.
So I wrote the following method to get the date of each day within the specified date range. The code is as follows:
<?php/** * 获取指定日期段内每一天的日期 * @param Date $startdate 开始日期 * @param Date $enddate 结束日期 * @return Array */function getDateFromRange($startdate, $enddate){ $stimestamp = strtotime($startdate); $etimestamp = strtotime($enddate); // 计算日期段内有多少天 $days = ($etimestamp-$stimestamp)/86400+1; // 保存每天日期 $date = array(); for($i=0; $i<$days; $i++){ $date[] = date('Y-m-d', $stimestamp+(86400*$i)); } return $date; }// demo$date = getDateFromRange('2016-02-25','2016-03-05'); print_r($date);?>
Output:
Array( [0] => 2016-02-25 [1] => 2016-02-26 [2] => 2016-02-27 [3] => 2016-02-28 [4] => 2016-02-29 [5] => 2016-03-01 [6] => 2016-03-02 [7] => 2016-03-03 [8] => 2016-03-04 [9] => 2016-03-05)
This article explains how to get the start date in PHP All dates between the end date and the end date. For more related content, please pay attention to the php Chinese website.
Related recommendations:
Interpretation of php's PDO connection to the database related content
How to implement recursive acquisition through php code The value of the specified key in an array
Reading a 1G file size through PHP
The above is the detailed content of php get all dates between start date and end date. For more information, please follow other related articles on the PHP Chinese website!