tags:

views:

59

answers:

3

I'm starting with 2010-05-01 and ending with 2010-05-10... how can I iterate through all of those dates?

+1  A: 

Converting to unix timestamps makes doing date math easier in php:

$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');

// Loop between timestamps, 24 hours at a time
for ($i = $startTime; $i <= $endTime; $i = $i + 86400) {
  $thisDate = date('Y-m-d', $i); // 2010-05-01, 2010-05-02, etc
}
Harold1983-
I don't like the look of that 86400. I understand that it is 60 * 60 * 24, but still... something about it irks me.
MikeD
+1 clever - Just make sure it's commented well, because this might not be apparent at first by just looking at it.
glowcoder
in this case, it works, but if there is a switch between normal and sunlight saving time, it will fail because there's a 90000 second-day that you'll have twice in your loop...
oezi
Mike, the best thing to do is setup a constant and name it "DAY" so it becomes far easier to read.
The Pixel Developer
+2  A: 
$startTime = strtotime('2010-05-01'); 
$endTime = strtotime('2010-05-10'); 

// Loop between timestamps, 1 day at a time 
$i = 1
do {
   $newTime = strtotime('+'.$i++.' days',$startTime); 
   echo $newTime;
} while ($newTime < $endTime);

or

$startTime = strtotime('2010-05-01'); 
$endTime = strtotime('2010-05-10'); 

// Loop between timestamps, 1 day at a time 
do {
   $startTime = strtotime('+1 day',$startTime); 
   echo $startTime;
} while ($startTime < $endTime);
Mark Baker
+5  A: 

Requires PHP5.3:

$begin = new DateTime( '2010-05-01' );
$end = new DateTime( '2010-05-10' );

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ( $period as $dt )
  echo $dt->format( "l Y-m-d H:i:s\n" );

This will output all days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. See the PHP Manuel for DatePeriod.

Gordon
+1 for use of DateTime, DateInterval and DatePeriod objects
Mark Baker
@Gordon, good news - there is a patch for setting a flag to include the end date which (fingers crossed) will make it into a future version.
salathe
@salathe Nice to know :)
Gordon