在这个带日期的while循环中我做错了什么?

时间:2014-07-10 13:56:42

标签: php

为什么while循环中的日期没有正确递增? (见代码评论) 有什么想法吗?

$d1 = strtotime($row['quote_valid_from']);
$d2 = strtotime($row['quote_valid_until']);
$min_date = min($d1, $d2);
//echo date('Y-m-d', $min_date).'<br>';  //(2012-01-01 - start of contract) 
$max_date = max($d1, $d2);           
//echo date('Y-m-d', $max_date).'<br>'; //(2014-12-31 end of contract)  
$ia = 0;  // set counter to 0
$nextdate = '';  // set next invoice date to 0
$prevdate = '';  // set previous invoice date to 0
while ($min_date <= $max_date) 
{
$nextdate = date('Y-m-d', strtotime($row['quote_valid_from'] . ' +'.$ia.' MONTHS'));  // start at 0 and increment at end of insert statement
$prevdate = date('Y-m-d', strtotime($nextdate . ' -1 MONTHS')); // for the previous invoice date, just decuct one month from the next invoice date
echo $prevdate.'<br>';  
echo $nextdate.'<br>';
// Here is the weird thing:  
// The latest date I get in my while loop is:  2012-08-01
// Insert happens now.
$ia++;  //increment $ia by 1
$min_date = strtotime('+'.$ia.' MONTHS', $min_date);  //add a month on to my minumum date for the while
} // end while 

由于 Ĵ

2 个答案:

答案 0 :(得分:2)

您应该使用DateTime。更清洁。此代码需要PHP 5.5:

$start = new DateTimeImmutable('2012-01-01');
$end   = new DateTimeImmutable('2014-12-31');
while($start <= $end) {
    $nextdate = $start->modify('+1 month');
    $prevdate = $start->modify('-1 month');
    echo $prevdate->format('Y-m-d').'<br>';  
    echo $nextdate->format('Y-m-d').'<br>';
    $start    = $nextdate;
}

其他要点:

  • 您的最小/最大概念是不必要的。您的开始日期应始终在结束日期之前。如果不是,那么你的软件存在很大问题。

适用于PHP 5.5.3或更早版本

$start = new DateTime('2012-01-01');
$end   = new DateTime('2014-12-31');
while($start <= $end) {
    $nextdate = clone $start;
    $nextdate->modify('+1 month');
    $prevdate = clone $start;
    $prevdate->modify('-1 month');
    echo $prevdate->format('Y-m-d').'<br>';  
    echo $nextdate->format('Y-m-d').'<br>';
    $start = $nextdate;
}

答案 1 :(得分:2)

问题是,您通过递增$min_date然后将其添加到$ia以指数方式递增$min_date,您只想为每次迭代添加一个月到$min_date 。即:

$min_date = strtotime('+1 MONTHS', $min_date);