如何在php中迭代一天


How to iterate day in php?

我需要得到接下来的7(或更多)日期,除了周日。首先我这样做

$end_date = new DateTime();
$end_date->add(new DateInterval('P7D'));
$period = new DatePeriod(
    new DateTime(),
    new DateInterval('P1D'),
    $end_date
);

,在foreach中检查$period后。但后来我注意到,如果我删除周日,我需要再添加一天到结束,这是每次当周日是…有什么办法吗?

$start = new DateTime('');
$end = new DateTime('+7 days');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
    if ($dt->format("N") === 7) {
        $end->add(new DateInterval('P1D'));
    }
    else  {
        echo $dt->format("l Y-m-d") . PHP_EOL;
    }
}

实际操作

我喜欢使用迭代器,以使实际的循环尽可能简单。

$days_wanted = 7;
$base_period = new DatePeriod(
    new DateTime(),
    new DateInterval('P1D'),
    ceil($days_wanted * (8 / 7)) // Enough recurrences to exclude Sundays
);
// PHP >= 5.4.0 (lower versions can have their own FilterIterator here)
$no_sundays = new CallbackFilterIterator(
    new IteratorIterator($base_period),
    function ($date) {
        return $date->format('D') !== 'Sun';
    }
);
$period_without_sundays = new LimitIterator($no_sundays, 0, $days_wanted);
foreach ($period_without_sundays as $day) {
    echo $day->format('D Y-m-d') . PHP_EOL;
}

您不能从DatePeriod中删除天数,但您可以简单地保留非星期日的计数并不断迭代,直到您累积了7天:

$date = new DateTime();
for ($days = 0; $days < 7; $date->modify('+1 day')) {
    if ($date->format('w') == 0) {
        // it's a Sunday, skip it
        continue;
    }
    ++$days;
    echo $date->format('Y-m-d')."'n";
}

您可以尝试使用UNIX时间,添加day,如果day是Sunday,则添加另一个。第一天你的名单将是eg。今天12点。然后再加上24 * 60 * 60得到第二天,以此类推。将UNIX转换为日很简单,使用date()函数。

$actDay = time();
$daysCount = 0;
while(true)
{
   if (date("D", $actDay) != "Sun") 
   {
     //do something with day
     $daysCount++;
   }
   if ($daysCount >= LIMIT) break;
   $actDay += 24 * 60 * 60;
}