在 PHP 中循环遍历 Unix 时间戳范围内的所有日期


Looping through all of the days within a Unix Timestamp range in PHP

假设你有两个像这样的Unix时间戳:

$startDate = 1330581600;
$endDate = 1333170000;

我想遍历该范围内的每一天并输出如下:

Start Loop
   Day Time Stamp: [Timestamp for the day within that loop]
End Loop

我尝试寻找某种类型的功能来执行此操作,但我不确定这是否可能。

由于我喜欢DateTime,DateInterval和DatePeriod,这是我的解决方案:

$start = new DateTime();
$end   = new DateTime();
$start->setTimestamp(1330581600);
$end->setTimestamp(1333170000);
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
foreach($period as $dt) {
  echo $dt->format('Y-m-d');
  echo PHP_EOL;
}

乍一看这似乎令人困惑,但这是一个非常合乎逻辑的方法。

使用 DatePeriod,您可以定义间隔为 1 天的时间段的开始和结束(在 DateInterval 中查找格式),然后您可以迭代它。
最后,在每次迭代中,您都会返回一个 DateTime 对象,您可以在该对象上使用DateTime::format()

for ($t = $start; $t < $end; $t = strtotime('+1 day', $t)) {
    ...
}