开发者

Adding number of days to a previous date inside incrementing variable for loop

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


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
)


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
}


$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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜