Reputation: 29
$start_date = strtotime('2011-08-21');
for($i=0 ; $i < 5; $i++)
{
echo "i = $i and ";
$start_date = mktime(0, 0, 0, date("m", $start_date), date("d", $start_date), date("Y", $start_date)+$i);
echo date('Y-m-d',$start_date)."<br /><hr />";
}
i = 0 and 2011-08-21
i = 1 and 2012-08-21
i = 2 and 2014-08-21
i = 3 and 2017-08-21
i = 4 and 2021-08-21
i didn't understand why after 2012 it doesn't add correctly.
Thanks
Upvotes: 0
Views: 298
Reputation: 749
Maybe you should do it like this if you want to add one year each time.
for($i=0 ; $i < 5; $i++)
{ echo "i = $i and ";
if($i>0) $start_date = mktime(0, 0, 0, date("m", $start_date), date("d", $start_date), date("Y", $start_date)+1);
echo date('Y-m-d',$start_date)."<br /><hr />";
}
Upvotes: 2
Reputation: 6431
It is working correctly. You're adding an incrementing number to the year on each iteration.
i = 0 and 2011-08-21 // 2011 + 0
i = 1 and 2012-08-21 // 2011 + 1
i = 2 and 2014-08-21 // 2012 + 2
i = 3 and 2017-08-21 // 2014 + 3
i = 4 and 2021-08-21 // 2017 + 4
You should either
+1
instead of +$1
to the year on each iteration$start_date
on each iterationfor($i=0 ; $i < 5; $i++)
{
echo "i = $i and ";
// $new_date holds the updated date without overwriting
$new_date = mktime(0, 0, 0, date("m", $start_date), date("d", $start_date), date("Y", $start_date)+$i);
echo date('Y-m-d', $new_date)."<br /><hr />";
}
Upvotes: 2
Reputation: 3586
The following line
$start_date = mktime(0, 0, 0, date("m", $start_date), date("d", $start_date), date("Y", $start_date)+$i);
Should be
$start_date = mktime(0, 0, 0, date("m", $start_date), date("d", $start_date), date("Y", $start_date)+1);
Otherwise the year of the date is being increased by 1 then 2 then 3 the 4, as teh start date is being modified each time.
Upvotes: 1