Home  >  Article  >  Backend Development  >  php get all dates between start date and end date

php get all dates between start date and end date

jacklove
jackloveOriginal
2018-06-08 23:34:261867browse

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(&#39;2016-06-01&#39;,&#39;2016-06-02&#39;,&#39;2016-06-03&#39;,&#39;2016-06-04&#39;,&#39;2016-06-05&#39;);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(&#39;Y-m-d&#39;, $stimestamp+(86400*$i));
    }    return $date;
}// demo$date = getDateFromRange(&#39;2016-02-25&#39;,&#39;2016-03-05&#39;);
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!

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