检查集合中的连续日期并返回范围

时间:2011-12-11 02:32:36

标签: php date

我有日期Y-m-d格式的数组,可以是相隔一天的十个设定日期的任意组合。

e.g。这是全套:

2011-01-01,2011-01-02,2011-01-03,2011-01-04,2011-01-05,2011-01-06,2011-01-07,2011-01-08 ,2011-01-09,2011-01-10

从该集合创建的数组可以是日期的任意组合 - 所有这些数组,其中一个,一些是连续的,都是连续的等等。

我现在让他们打印得非常好。例如这是一个可能的结果:

2011-01-02

2011-01-03

2011-01-04

2011-01-08

(实际印刷的内容更像是“1月2日星期五......”,但我们会坚持使用简单的日期字符串)

我想缩小它,以便如果连续三天或更多天,那些就成了一个范围,例如上面的例子就会变成:

2011-01-02至2011-01-04

2011-01-08

最终将成为:

1月2日星期日 - 1月4日星期二

1月8日星期六

有没有办法循环并检查时差,为范围创建开始时间和结束时间,然后收集落后者?

1 个答案:

答案 0 :(得分:13)

快速回答有点抱歉没有实现,但假设您使用的是5.3并且日期是按时间顺序排序的,您可以将每个日期转换为DateTime对象(如果它们还没有)和然后使用DateTime::diff()遍历数组以生成DateInterval对象,您可以使用该对象将迭代中的当前日期与最后一个日期进行比较。您可以将连续日期分组为子数组,并使用shift()pop()来获取该子数组中的第一天和最后一天。

修改

我想到了这一点。接下来是非常粗略和准备好的实现,但它应该有效:

// assuming a chronologically
// ordered array of DateTime objects 

$dates = array(
    new DateTime('2010-12-30'), 
    new DateTime('2011-01-01'), 
    new DateTime('2011-01-02'), 
    new DateTime('2011-01-03'), 
    new DateTime('2011-01-06'), 
    new DateTime('2011-01-07'), 
    new DateTime('2011-01-10'),
);

// process the array

$lastDate = null;
$ranges = array();
$currentRange = array();

foreach ($dates as $date) {    

    if (null === $lastDate) {
        $currentRange[] = $date;
    } else {

        // get the DateInterval object
        $interval = $date->diff($lastDate);

        // DateInterval has properties for 
        // days, weeks. months etc. You should 
        // implement some more robust conditions here to 
        // make sure all you're not getting false matches
        // for diffs like a month and a day, a year and 
        // a day and so on...

        if ($interval->days === 1) {
            // add this date to the current range
            $currentRange[] = $date;    
        } else {
            // store the old range and start anew
            $ranges[] = $currentRange;
            $currentRange = array($date);
        }
    }

    // end of iteration... 
    // this date is now the last date     
    $lastDate = $date;
}

// messy... 
$ranges[] = $currentRange;

// print dates

foreach ($ranges as $range) {

    // there'll always be one array element, so 
    // shift that off and create a string from the date object 
    $startDate = array_shift($range);
    $str = sprintf('%s', $startDate->format('D j M'));

    // if there are still elements in $range
    // then this is a range. pop off the last 
    // element, do the same as above and concatenate
    if (count($range)) {
        $endDate = array_pop($range);
        $str .= sprintf(' to %s', $endDate->format('D j M'));
    }

    echo "<p>$str</p>";
}

输出:

Thu 30 Dec
Sat 1 Jan to Mon 3 Jan
Thu 6 Jan to Fri 7 Jan
Mon 10 Jan