栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

一个简单的答案,对于缺乏实现感到抱歉,但是假设您使用的是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 datesforeach ($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 DecSat 1 Jan to Mon 3 JanThu 6 Jan to Fri 7 JanMon 10 Jan


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/443161.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号