//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
$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);
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;
}
我希望你会喜欢这些恶心的把戏。对这段代码的许多部分尝试了许多方法,这个版本到目前为止是一个明显的赢家,但我愿意接受建议。(除了在静态变量中缓存以供后续调用之外。这是作弊我完全可以做到这一点,但仍然)。 more about this如果你喜欢。
4条答案
按热度按时间nx7onnlm1#
像这样的东西应该可以做到:
基本上,将日期转换为时间戳,并在每个循环中添加一天。
siv3szwd2#
使用PHP的
DateTime
库:Source
wsewodh23#
试试这个:
8fsztsew4#
超快版本
日期转换是昂贵的。我对表演很失望,所以我试着调整了一下速度。它更像是一个优化的案例研究,但我将把它留在这里,因为它几乎比平常快3倍。它的工作原理是减少
date( )
被调用的次数。我希望你会喜欢这些恶心的把戏。对这段代码的许多部分尝试了许多方法,这个版本到目前为止是一个明显的赢家,但我愿意接受建议。(除了在静态变量中缓存以供后续调用之外。这是作弊我完全可以做到这一点,但仍然)。
more about this如果你喜欢。