0

我有两个日期(开始和结束),例如:

$date['start'] = '2012-07-11';
$date['end'] = '2012-07-13';

我想为此生成-4 天和+4 天的间隔。所以我想收到例如数组:

$date['start'] = '2012-07-07';
$date['end'] = '2012-07-09';

$date['start'] = '2012-07-08';
$date['end'] = '2012-07-10';

$date['start'] = '2012-07-09';
$date['end'] = '2012-07-11';

$date['start'] = '2012-07-10';
$date['end'] = '2012-07-12';

$date['start'] = '2012-07-11';
$date['end'] = '2012-07-13';

$date['start'] = '2012-07-12';
$date['end'] = '2012-07-14';

$date['start'] = '2012-07-13';
$date['end'] = '2012-07-15';

$date['start'] = '2012-07-14';
$date['end'] = '2012-07-16';

$date['start'] = '2012-07-15';
$date['end'] = '2012-07-17';

最好的方法是什么?

4

3 回答 3

0

这段代码可以解决问题:

 $date['start'] = '2012-07-11';
 $date['end'] = '2012-07-13';

 $dates=array();
 for ($i=-4; $i<=4; $i++){
   $startDate=strtotime($date['start'] );
   $endDate=strtotime($date['end'] );

   $startDate=$startDate+($i*60*60*24); //60*60*24 equal to one day
   $endDate=$endDate+($i*60*60*24);

   array_push($dates, array('start'=>date('Y-m-d', $startDate), 'end'=> date('Y-m-d',$endDate)));
 }
 print_r($dates);

输出:

Array(
    [0] => Array
        (
            [start] => 2012-07-07
            [end] => 2012-07-09
        )

    [1] => Array
        (
            [start] => 2012-07-08
            [end] => 2012-07-10
        )

    [2] => Array
        (
            [start] => 2012-07-09
            [end] => 2012-07-11
        )

    [3] => Array
        (
            [start] => 2012-07-10
            [end] => 2012-07-12
        )

    [4] => Array
        (
            [start] => 2012-07-11
            [end] => 2012-07-13
        )

    [5] => Array
        (
            [start] => 2012-07-12
            [end] => 2012-07-14
        )

    [6] => Array
        (
            [start] => 2012-07-13
            [end] => 2012-07-15
        )

    [7] => Array
        (
            [start] => 2012-07-14
            [end] => 2012-07-16
        )

    [8] => Array
        (
            [start] => 2012-07-15
            [end] => 2012-07-17
        )

)
于 2012-07-11T15:01:27.097 回答
0

您想要从提供范围的 -4 天到 +4 天的 9 对日期?

假设您的日期将在 1970 年之后:

<?php
$start=strtotime($date['start']);
$end=strtotime($date['end']);

for($loop=-4;$loop<=4;$loop++)
{
    $loop_str='';
    if($loop>=0) $loop_str.='+';
    $loop_str.=$loop.' days';
    $date['start']=strtotime($loop_str, $start);
    $date['end']=strtotime($loop_str, $end);
    print_r($date);
}
?>
于 2012-07-11T14:39:12.857 回答
0

range(date('Ymd', strtotime('-4 days'), date('Ymd', strtotime('+4 days'))),

于 2012-07-11T14:17:18.853 回答