php循环通过不超过月结束日期的日期

时间:2013-09-17 06:35:23

标签: php date datetime

以下是我的脚本,适用于除29,30和31之外的所有开始日期。任何人都可以使它适用于从1开始的所有日期.... 31它应该按月递增并且不要超过上次日期?< / p>

  $startdate='2010-01-30';
  $enddate='2011-01-30';
    while ($startdate <= $enddate)
     { 
      echo date('Y-m-d', $startdate ) . "\n";
      $startdate = strtotime('+1 month', $startdate);
    }

3 个答案:

答案 0 :(得分:5)

试试这个

<?php
  $startdate='2010-01-31';
  $enddate='2011-01-31';
    $timestamp=  strtotime($startdate);
    while ($startdate <= $enddate)
     { 
      $startdate = date('Y-m-t', $timestamp);
      echo $startdate . "<br/>";
      $timestamp = strtotime('+1 days', strtotime($startdate));
    }
?>

答案 1 :(得分:0)

尝试

<?php
    $startdate = strtotime('2010-01-29');
    $enddate = strtotime('2011-01-31');
$inc = 1;
    while($startdate <= $enddate )
    {
        $date = date("t", $startdate);
        $numbersofdays = date('d',$startdate);
        $incDate = ($date - $numbersofdays) + 1;
        if ($startdate == $enddate || $inc==1) {
            echo date('Y-m-d',$startdate).  PHP_EOL;
        } else {
        echo date('Y-m-t',$startdate).  PHP_EOL;
       }

         $startdate = strtotime("+".$incDate." days", $startdate );
        $inc++;
    }
?>

答案 2 :(得分:0)

这看起来像复杂的代码,但我相信这就是你所需要的。

<?php
$startDate='2010-01-29';
$endDate='2013-12-30';
$startDateSplit = explode("-",$startDate);
$endDateSplit = explode("-",$endDate);
$starTime = mktime(0, 0, 0, $startDateSplit[1], $startDateSplit[2], $startDateSplit[0]);
$numDaysStart = $startDateSplit[2];
$passThroughDelta = false;
$endTime = mktime(0, 0, 0, $endDateSplit[1], $endDateSplit[2], $endDateSplit[0]);
while ($starTime <= $endTime)
{
      $startDate = date('Y-m-d', $starTime);
      echo $startDate . "\n";
      $startDateSplit = explode("-",$startDate);
      $numDays = cal_days_in_month(CAL_GREGORIAN, $startDateSplit[1],$startDateSplit[0]);
      echo $numDays . "\n";
      if($startDateSplit[1] == 12) {
         $startDateSplit[1] = 0;
         $startDateSplit[0]++;
      }
      if($numDaysStart > cal_days_in_month(CAL_GREGORIAN,     $startDateSplit[1]+1,$startDateSplit[0])) {
       $delta = $numDaysStart - cal_days_in_month(CAL_GREGORIAN,     $startDateSplit[1]+1,$startDateSplit[0]);
           $numDays = $numDays - $delta;
           $passThroughDelta = true;
      }
      else if ($passThroughDelta) {
           $numDays = $numDays + $delta;
           $passThroughDelta = false;
      }
      $starTime = mktime(0, 0, 0, $startDateSplit[1], $startDateSplit[2]+$numDays,     $startDateSplit[0]);
}