我想在for循环的每次迭代中为截止日期添加1个月。这是我的代码,如下所示。
$qt = 3;
$sales_due_date = 2015-09-21;
for($i=0;$i<$qt;$i++){
$time = date('Y-m-d', strtotime('+1 month', strtotime($sales_due_date)));
$due_dates[] = $time;
}
结果是
Array ( [0] => 2015-10-21 [1] => 2015-10-21 [2] => 2015-11-21)
我希望结果如下所示
Array ( [0] => 2015-09-21 [1] => 2015-10-21 [2] => 2015-11-21)
答案 0 :(得分:3)
您的代码不会更新$ sales_due_date,因此它将始终返回相同的值。另外,如果您想要起始值,则需要稍微更改逻辑。也许这对你来说可能更好:
$qt = 3;
$sales_due_date = "2015-09-21";
// create a time stamp of the date
$time = strtotime($sales_due_date);
for($i=0;$i<$qt;$i++){
// convert timestamp back to date string
$date = date('Y-m-d', $time);
$due_dates[] = $date;
// move to next timestamp
$time = strtotime('+1 month', $time)
}
答案 1 :(得分:1)
这应该给出预期的结果
$qt = 3;
$sales_due_date = "2015-09-21";
for ($i = 0; $i < $qt; $i++)
{
$due_dates[] = $sales_due_date;
$time = date('Y-m-d', strtotime('+1 month', strtotime($sales_due_date)));
$sales_due_date = $time;
}
output
Array
(
[0] => 2015-09-21
[1] => 2015-10-21
[2] => 2015-11-21
)
答案 2 :(得分:0)
试试这个
$qt = 3;
$sales_due_date = 2015-09-21;
$time="";
for($i=0;$i<$qt;$i++){
if($time == "")
{
$time = date('Y-m-d', strtotime('+1 month', strtotime($sales_due_date)));
}
else{
$time = date('Y-m-d', strtotime('+1 month', strtotime($time)));
}
$due_dates[] = $time;
}