【问题标题】:Splitting a start and end date by interval in PHP [duplicate]在PHP中按间隔拆分开始日期和结束日期[重复]
【发布时间】:2012-03-07 22:46:21
【问题描述】:

是否有任何功能可以将开始日期和结束日期分成$interval 天(或月)的块?例如:

$interval = new DateInterval('P10D');
$start    = new DateTime('2012-01-10');
$end      = new DateTime('2012-02-16');

$chunks = splitOnInterval($start, $end, $interval);

// Now chunks should contain
//$chunks[0] = '2012-01-10'
//$chunks[1] = '2012-01-20'
//$chunks[2] = '2012-01-30'
//$chunks[3] = '2012-02-09'
//$chunks[3] = '2012-02-16'

我认为DatePeriod 可以提供帮助,但我没有找到任何使用方法。

【问题讨论】:

标签: php datetime dateinterval


【解决方案1】:

how to iterate over valid calender days查看这篇文章。

在 php 中类似于,

$start = strtotime('2012-01-10');
$end1 = strtotime('2012-02-16');
$interval   = 10*24*60*60; // 10 days equivalent seconds.
$chunks = array();
for($time=$start; $time<=$end1; $time+=$interval){
    $chunks[] = date('Y-m-d', $time);
}

【讨论】:

  • 如果我必须将 18 个月 (2017-01-01, 2018-30-06) 分成相等的 5 个月,那么我需要在上面的代码中进行哪些更改? .
【解决方案2】:

这是一个迭代数天的示例,一个月内与其他间隔相应地工作

<?php

$begin = new DateTime( '2012-11-01' );
$end = new DateTime( '2012-11-11' );
$end = $end->modify( '+1 day' );

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach($daterange as $date){
echo $date->format("Y-m-d") . "<br>";
}
?>

【讨论】: