拆分日期范围

时间:2015-06-02 19:22:16

标签: php

我试图将日期范围分成相等的部分

我试试:

    function splitDates($min, $max, $parts = 7, $output = "Y-m-d") {
        $dataCollection = array();
        $diff = (strtotime($max) - strtotime($min)) / $parts;
        for ($i = 1; $i <= $parts; $i++) {
            $convert = $i == 1 ? $min : end($dataCollection);
            $dataCollection[] = $i !== $parts ? date($output, strtotime($convert) + $diff) : date($output, strtotime($max));
        }

        return $dataCollection;
    }

    $min = "2014-01-01";
    $max = "2016-01-01";
    $dates = splitDates($min, $max);

    echo "<pre>";
    $i = 0;
    foreach ($dates as $value) {
        $i++;
        echo "data $i  : $value <br>";
    }
    echo "</pre>";

输出:

date 1  : 2014-04-15 
date 2  : 2014-07-28 
date 3  : 2014-11-09 
date 4  : 2015-02-21 
date 5  : 2015-06-05 
date 6  : 2015-09-17 
date 7  : 2016-01-01 

结果不符合预期,第一个日期始终为$ min,最后一个日期始终为$ max

日期之间的间隔不准确

1 个答案:

答案 0 :(得分:2)

我稍微简化了你的代码并开始工作

 function splitDates($min, $max, $parts = 7, $output = "Y-m-d") {
        $dataCollection[] = date($output, strtotime($min));
        $diff = (strtotime($max) - strtotime($min)) / $parts;
        $convert = strtotime($min) + $diff;

        for ($i = 1; $i < $parts; $i++) {
            $dataCollection[] = date($output, $convert);
            $convert += $diff;
        }
        $dataCollection[] = date($output, strtotime($max));
        return $dataCollection;
    }