PHP循环 - 添加日期

时间:2014-04-24 09:57:38

标签: php date loops

我有以下代码。它可以将日期(daysBetween)添加到日期(startDate)。但是,我想重复它直到它到达结束日期。我怎么能这样做?

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

2 个答案:

答案 0 :(得分:3)

您可以使用以下功能;

<?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);

以下是一个有效的演示: Demo

答案 1 :(得分:1)

   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;

    }