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

Tal*_*lon 3 php loops strtotime

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

$startDate = 1330581600;
$endDate = 1333170000;
Run Code Online (Sandbox Code Playgroud)

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

Start Loop
   Day Time Stamp: [Timestamp for the day within that loop]
End Loop
Run Code Online (Sandbox Code Playgroud)

我曾尝试寻找某种类型的功能来做到这一点,但我不确定它是否可能.

Dan*_*Lee 8

我喜欢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;
}
Run Code Online (Sandbox Code Playgroud)

这一开始似乎令人困惑,但这是一种非常合理的方法.

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

  • +1使用`DateTime`系列类,因为它们非常令人敬畏. (3认同)