2014-07-10 29 views
0

为什么while循环中的日期不能正确递增? (见代码评论) 任何想法?我在这个带日期的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 

感谢 Ĵ

+0

定义“一个月”。 31天? 30? 28? ... 29? –

+0

你使用的是什么版本的PHP? –

回答

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; 
} 
+0

美丽的答案,谢谢http://stackoverflow.com/users/250259/john-conde – Jacques

+0

你确定这段代码是正确的吗?问题是$ start和$ end似乎不是可比的变量,而是一个类的实例,所以while循环永远不会进入?有任何想法吗? – Jacques

+0

DateTime及其相关类是可比较的。这是它如此强大的原因之一。 [这是一个小提琴,显示它的工作](http://3v4l.org/0Cakv)。 –

2

的问题是,你是通过增加$ia,然后补充说,到$min_date,你只是想一个月增加$min_date成倍递增$min_date为每个迭代。即:

$min_date = strtotime('+1 MONTHS', $min_date); 
相关问题