PHP 循环访问不超过月结束日期的日期


php loop through dates not exceeding month ending date

下面是我的脚本,它适用于所有开始日期,除了 29,30 和 31。任何人都可以让它适用于从 1....31st 开始的所有日期,它应该按月递增并且不超过最后一个日期?

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

试试这个

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

尝试

<?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++;
    }
?>

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

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