编辑 2:
我已经用一些日期格式更新了函数。
输出将是:
活动标题
时间:2010 年 2 月 28 日 - 2010 年 3 月 2 日
活动标题
时间:2010 年 3 月 4 日 - 2010 年 3 月 5 日
活动标题
时间:2010 年 12 月 31 日 - 2011 年 1 月 5 日
编辑:
我找到了这个(通过搜索)--> Check for consecutive dates within a set and return as range
下面的代码不是我的。这是@Darragh的旧帖子
我对代码做了一些小改动以适应 OP 的问题。
// assuming a chronologically
// ordered array of DateTime objects
$dates = array(
new DateTime('2010-02-28'),
new DateTime('2010-03-01'),
new DateTime('2010-03-02'),
new DateTime('2010-03-04'),
new DateTime('2010-03-05'),
new DateTime('2010-12-31'),
new DateTime('2011-01-01'),
new DateTime('2011-01-02'),
new DateTime('2011-01-03'),
new DateTime('2011-01-04'),
new DateTime('2011-01-05'),
);
// 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 = "<h4>Event title</h4>";
$str .= "<p>When: ";
$str .= "<time>";
$str .= sprintf('%s', $startDate->format('M j, Y'));
// 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(' - %s', $endDate->format('M j, Y'));
$str .= "</time></p>";
}
echo "<p>$str</p>";
}
旧答案(基于原始问题)。
$start_date = new DateTime( '2015-05-01' );
$end_date = new DateTime( '2015-05-04' );
$end_date = $end_date->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($start_date, $interval ,$end_date);
foreach($daterange as $date){
echo $date->format("M d, Y") . "<br>";
}
// Output
// May 01, 2015
// May 02, 2015
// May 03, 2015
// May 04, 2015