简体   繁体   中英

PHP loop - add days to date

I have the following code. It works to add days (daysBetween) to a date (startDate). However, I want to REPEAT it until it reaches the end date. How can I do this??

$startDate = "2009-10-11";
$endDate = "2010-01-20";
$daysBetween = 10;

function addDayswithdate($date,$days){

  $date = strtotime("+".$days." days", strtotime($date));
  return  date("Y-m-d", $date);

}

$date = addDayswithdate($startDate,$daysBetween);

You can use following function;

<?php

$startDate = "2009-10-11";
$endDate = "2010-01-20";
$daysBetween = 10;
$finalResult = array();
function addDayswithdate($date,$days, $endDate, &$finalResult){
  $tempDate = strtotime($date);
  $tempDate += 3600*24*$days;
  if ($tempDate < strtotime($endDate)) {
    $finalResult[] = date("Y-m-d", $tempDate);
    addDayswithdate(date("Y-m-d", $tempDate), $days, $endDate, $finalResult);
  } else {
    return true;        
  }
}

addDayswithdate($startDate,$daysBetween, $endDate, $finalResult);
var_dump($finalResult);

Here is a working demo: Demo

   function addDayswithdate($from, $to, $interval){

        $result = array();
        while(true)
        {
            $dateTemp = strtotime("+".$interval." days", strtotime($from));
            if(strtotime($dateTemp) > strtotime($to)) 
                break;
            $result[] = date("Y-m-d", $dateTemp);
            $interval += $interval;
        }
        return  $result;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM