PHP获取两个日期之间的所有日期

本文章向大家介绍php获取开始与结束日期之间所有日期的方法。比如给定两个日期: 2021-04-05 和2021-04-07,返回这两个日期之间的所有日期时间,结果为:

2021-04-05

2021-04-06

2021-04-07

这里我们向大家介绍两种不同的方法实现这一需求。

  1. 第一种方法:使用PHP DatePeriod()类获取两个日期之间的所有日期
  2. 第二种方法:使用PHP strtotime()函数获取两个日期之间的所有日期

 

PHP DatePeriod()类

PHP DatePeriod 类表示一个时间周期。一个时间周期可以用来在给定的一段时间之内, 以一定的时间间隔进行迭代。

DatePeriod属性如下:

recurrences:如果通过显式的传入 $recurrences 来创建的 DatePeriod 实例, 那么这个参数表示循环次数。 

include_start_date:在循环过程中,是否包含开始时间。

start:时间周期的开始时间。

current:表示在时间周期内迭代的时候,当前的时间。

end:时间周期的结束时间。

interval:ISO 8601 格式的间隔。

我们可以使用DatePeriod()获取两个日期之间的日期。如下:

$period = new DatePeriod(
     new DateTime('2020-10-01'),
     new DateInterval('P1D'),
     new DateTime('2020-10-05')
);

上面的代码将为您提供一个包含DateTime对象的数组,然后可以使用它 foreach 来输出每个日期。

foreach ($period as $key => $value) {
    $value->format('Y-m-d');    
}

结果:

2020-10-01
2020-10-02
2020-10-03
2020-10-04

将上面的示例封装为一个php函数,然后调用这个函数直接输出两个给定日期之间的所有日期。代码如下:

/**
 * Returns every date between two dates as an array
 * @param string $startDate the start of the date range
 * @param string $endDate the end of the date range
 * @param string $format DateTime format, default is Y-m-d
 * @return array returns every date between $startDate and $endDate, formatted as "Y-m-d"
 */
function createDateRange($startDate, $endDate, $format = "Y-m-d")
{
    $begin = new DateTime($startDate);
    $end = new DateTime($endDate);

    $interval = new DateInterval('P1D'); // 1 Day
    $dateRange = new DatePeriod($begin, $interval, $end);

    $range = [];
    foreach ($dateRange as $date) {
        $range[] = $date->format($format);
    }

    return $range;
}
$all_dates=createDateRange("2015-01-01", "2015-02-05");
print_r($all_dates);

 这将返回两个日期之间的所有日期的数组,如下所示:

Array
(
    [0] => 2015-01-01
    [1] => 2015-01-02
    [2] => 2015-01-03
    [3] => 2015-01-04
    [4] => 2015-01-05
    [5] => 2015-01-06
    [6] => 2015-01-07
)

 

PHP strtotime()函数

strtotime() 函数将任何字符串的日期时间描述解析为 Unix 时间戳,我们可以先将开始日期和结束日期转化为Unix 时间戳,然后从开始日期循环到结束日期,并输出两者之间的所有日期。

示例代码如下:

<?php
    // Specify the start date. This date can be any English textual format  
    $date_from = "2020-10-01";  
    $date_from = strtotime($date_from); // Convert date to a UNIX timestamp  
      
    // Specify the end date. This date can be any English textual format  
    $date_to = "2020-10-05";  
    $date_to = strtotime($date_to); // Convert date to a UNIX timestamp  
      
    // Loop from the start date to end date and output all dates inbetween  
    for ($i=$date_from; $i<=$date_to; $i+=86400)
    {
        echo date("Y-m-d", $i).'<br />';  
    }  
?>

结果:

2020-10-01
2020-10-02
2020-10-03
2020-10-04
2020-10-05
 以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家
posted @ 2022-08-24 13:06  small_123  阅读(1191)  评论(0编辑  收藏  举报