doudu3961
2010-12-31 00:29
浏览 73
已采纳

在循环递增变量内添加上一个日期的天数

I am working on a function which adds a number of days to a date inside an incrementing variable loop. I am having a problem getting the date from the previous loop to add the next 30 days to that date. This seems to be working for the first 2 loops then breaks and I cannot figure out the correct code to get the previous dates.

Here is my code:

$pay_cycles=5;
$period=30;

 $arr = array();
 for ($i=1;$i<=$pay_cycles;$i++) {

 //if first loop get todays date
 if($i==1){
 $due = date("Y-m-d");

 //else add to previous date
 } else {
 $time = strtotime ( '+'.$period.' day' , strtotime ( $due-1 ) ) ;
 $due = date("Y-m-d", $time); 
 }
   $arr[] = $due;
 }
 print_r($arr);

This is what prints

Array ( [0] => 2010-12-30 [1] => 2011-01-29 [2] => 2011-01-29 [3] => 2011-01-29 [4] => 2011-01-29 )

Thanks for looking

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douban2014 2010-12-31 00:53
    已采纳

    Maybe I am not understanding your requirement completely: but to get the next 5 X 30 day periods:

    $pay_cycles=5;
    $period=30;
    
     $arr = array();
     for ($i=1;$i<=$pay_cycles;$i++) {
    
     //if first loop get todays date
     if($i==1){
     $due = date("Y-m-d");
    
     //else add to previous date
     } else {
     $time = strtotime ( "$due +$period day" ) ;
     $due = date("Y-m-d", $time); 
     }
       $arr[] = $due;
     }
     print_r($arr);
    

    Gives:

    Array
    (
        [0] => 2010-12-31
        [1] => 2011-01-30
        [2] => 2011-03-01
        [3] => 2011-03-31
        [4] => 2011-04-30
    )
    
    打赏 评论
  • doupu5941 2010-12-31 00:35

    This: strtotime ( $due-1 ) is probably biting you. $due is a string, containing "2010-12-31", and subtracting 1 will result in 2010-1 = 2009.

    Have a look at mktime(). E.g.

    $d = date("d");
    $m = date("m");
    $y = date("Y");
    
    $pay_cycles = 5;
    $period = 30;
    
    for ( $i=0;$i<$pay_cycles;$i++ )
    {
        $ts = mktime(0,0,0,$m,$d+$i*$period,$y);
        $datestr = date("Y-m-d",$ts);
        // stuff with $datestr
    }
    
    打赏 评论
  • duanmu6752 2010-12-31 01:14
    $pay_cycles=5;
    $period=30;
    
     $arr = array();
     for ($i=0;$i<$pay_cycles;$i++) {
     if($i==0){
     $due = date("Y-m-d");
    
     //else add to previous date
     } else {
    
     $time = mktime(0,0,0,date("m"),date("d")+30*$i,date("Y"));
     $due = date("Y-m-d", $time); 
    }
       $arr[] = $due;
     }
     print_r($arr);
    
    打赏 评论

相关推荐 更多相似问题