Reputation: 1884
How to add a date with DateInterval for specified variable?
<?php
$begin = new DateTime('2010-01-01 08:00');
$end = new DateTime( '2010-01-05 20:00');
$interval = new DateInterval('P1D');
$period = new DatePeriod($begin, $interval, $end);
foreach ( $period as $dt ) {
$tempBegin = $tempEnd = $dt;
$tempEnd->add(new DateInterval('P1D'));
echo $tempEnd->format( "Y-m-d H:i" ) . '<br/>';
echo $tempBegin->format( "Y-m-d H:i" ) . '<br/>';
}
It will give result like this :
2010-01-02 08:00
2010-01-02 08:00
2010-01-03 08:00
2010-01-03 08:00
2010-01-04 08:00
2010-01-04 08:00
2010-01-05 08:00
2010-01-05 08:00
2010-01-06 08:00
2010-01-06 08:00
I want to add 1 day just for $tempBegin
variable.
Upvotes: 1
Views: 143
Reputation: 781210
When you assign objects, you don't make copies. So the variables $tempBegin
and $tempEnd
both refer to the same object, and when you modify it with add()
it modifies the object that both variables refer to.
You need to clone the object:
$tempBegin = $dt;
$tempEnd = clone $tempBegin;
$tempEnd->add(new DateInterval('P1D'));
Upvotes: 3