我需要生成一个日期列表(使用php或mysql或两者),其中指定了开始和结束日期?例如,如果开始日期是2012-03-31,结束日期是2012-04-05,我如何生成这样的列表?
2012-03-31
2012-04-01
2012-04-02
2012-04-03
2012-04-04
2012-04-05
我有一个mysql表,上面有开始和结束日期,但我需要完整的日期列表。
应该这样做:
//Get start date and end date from database
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$date_list = array($start_date);
$current_time = $start_time;
while($current_time < $end_time) {
//Add one day
$current_time += 86400;
$date_list[] = date('Y-m-d',$current_time);
}
//Finally add end date to list, array contains all dates in order
$date_list[] = $end_date;
基本上,将日期转换为时间戳,并在每个循环中添加一天。
使用PHP的DateTime
库:
<?php
$start_str = '2012-03-31';
$end_str = '2012-04-05';
$start = new DateTime($start_str);
$end = new DateTime($end_str . ' +1 day'); // note that the end date is excluded from a DatePeriod
foreach (new DatePeriod($start, new DateInterval('P1D'), $end) as $day) {
echo $day->format('Y-m-d'), "n";
}
源
试试这个:
<?php
// Set the start and current date
$start = $date = '2012-03-31';
// Set the end date
$end = '2012-04-05';
// Set the initial increment value
$i = 0;
// The array to store the dates
$dates = array();
// While the current date is not the end, and while the start is not later than the end, add the next day to the array
while ($date != $end && $start <= $end)
{
$dates[] = $date = date('Y-m-d', strtotime($start . ' + ' . $i++ . ' day'));
}
// Output the list of dates
print_r($dates);
超快速版本
日期转换成本高昂。我对表演感到失望,所以我试着把它调快一点。这更像是一个优化的案例研究,但我将把它留在这里,因为它几乎比平时快3倍。它的工作原理是减少调用date( )
的次数。
function listDaysBetween($from,$till) {
if($till<$from) return[]; // handle the obvious empty case
$tsFrom = strtotime("$from 11:00"); // middle of first day
$tsTill = strtotime("$till 11:00"); // middle of last day
$tsDiff = $tsTill - $tsFrom; // seconds diff
$diff = round($tsDiff/86400); // days diff; output length
$ts = $tsFrom; // $ts will follow us along
$day = $from; // $day will scan the range
$days = [$day]; // put the first one in there
while($diff-->0) { // a disguised for-loop
$ts+=86400; // keep timestamp following
$d = (int)($day[8].$day[9]); // get the day part (fast)
if($d>27) { // at the end of each month,
$day = date("Y-m-d",$ts); // it's better to ask date()
}else{ // otherwise we do it faster
$d+=101; $d="$d"; // zero-padding to 2 digits
$day[8] = $d[1]; // direct character replace
$day[9] = $d[2]; // is faster than substr()
}
$days[] = $day; // build output array
}
return $days;
}
我希望你会喜欢这些卑鄙的把戏。对这段代码的许多部分尝试了很多方法,到目前为止,这个版本是一个明显的赢家,但我愿意接受建议。(除了在静态变量中缓存以供后续调用之外。这是欺骗。我完全会这么做,但仍然如此。)
如果你喜欢的话,请阅读更多关于这方面的内容。
注意:此函数没有输入控制,您至少需要一些正则表达式,以避免在使用伪数据调用时出现意外的无休止循环。为了简洁起见,我省略了那些行