Quoting all days within the Unix time frame in PHP

Say you are given two Unix timestamps:

$startDate = 1330581600;
$endDate = 1333170000;

I want to scroll every day in this range and output it something like this:

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

I tried looking for some function for this, but I'm not sure if this is possible.

+3
source share
2 answers

As I like DateTime, DateInterval and DatePeriod, here is my solution:

$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;
}

It seems like this is confusing at first, but this is a very logical approach.

DatePeriod 1 ( DateInterval), .
, DateTime, DateTime::format()

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

All Articles