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

php get all dates between start date and end date

jacklove
Release: 2023-03-31 06:26:01
Original
1903 people have browsed it

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){    // 执行处理}?>
Copy after login

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);?>
Copy after login

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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template