I'm starting with 2010-05-01 and ending with 2010-05-10... how can I iterate through all of those dates?
views:
59answers:
3
+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-
2010-07-08 20:35:58
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
2010-07-08 20:37:26
+1 clever - Just make sure it's commented well, because this might not be apparent at first by just looking at it.
glowcoder
2010-07-08 20:37:31
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
2010-07-08 20:46:36
Mike, the best thing to do is setup a constant and name it "DAY" so it becomes far easier to read.
The Pixel Developer
2010-07-08 20:50:20
+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
2010-07-08 20:42:59
+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
2010-07-08 20:43:40
@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
2010-07-08 20:51:40