65

我正在尝试列出两个日期之间的所有月份。

例如; 开始日期是:2010-12-02最后日期是:2012-05-06

我想列出这样的内容:

2010-12
2011-01
2011-02
2011-03
2011-04
.
.
.
2012-04
2012-05

这是我尝试过的,但它根本不起作用:

    $year_min = 2010;
    $year_max = 2012;
    $month_min = 12;
    $month_max = 5;
    for($y=$year_min; $y<=$year_max; $y++)
    {
        for($m=$month_min; $m<=$month_max; $m++)
        {
            $period[] = $y.$m;
        }
    }
4

6 回答 6

220

PHP 5.3

$start    = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end      = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("Y-m") . "<br>\n";
}

看到它在行动

PHP 5.4 或更新版本

$start    = (new DateTime('2010-12-02'))->modify('first day of this month');
$end      = (new DateTime('2012-05-06'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("Y-m") . "<br>\n";
}

我们将开始日期和结束日期修改为月初的部分很重要。如果我们不这样做,并且当前日期高于二月的最后一天(即非闰年为 28,闰年为 29),这将跳过二月。

于 2013-09-11T13:46:37.413 回答
10

您必须区分同一年的两个月和不同年份的两个月。

$year_min = substr($row['contractStart'], 0, 4);
$year_max = substr($row['contractEnd'], 0, 4);
$month_min = substr($row['contractStart'], 5, 2);
$month_min = substr($row['contractEnd'], 5, 2);
$period = array();
try {
  if ($year_min > $year_max)
    throw new Exception();
  else if ($year_min == $year_max)
    if ($month_min > $month_max)
      throw new Exception();
    for ($month = $month_min; $month <= $month_max; $month++) {
      $period[] = $month . '-' . $year;
    }
  else {
    for ($month = $month_min; $month <= 12; $month++) {
      $period[] = $month . '-' . $year_min;
    }
    for ($year = $year_min + 1; $year < $year_max; $year++) {
      for ($month = $month_min; $month <= $month_max; $month++) {
        $period[] = $month . '-' . $year;
      }
    }
    for ($month = 1; $month <= $month_max; $month++) {
      $period[] = $month . '-' . $year_max;
    }
  }
  implode("<br />\r\n", $period);
}
catch (Exception $e) {
  echo 'Start date occurs after end date.'
}

那是困难的方式。现在已经给出了一种快速简便的方法作为答案,我建议您选择。

于 2013-09-11T13:59:24.157 回答
9
function getMonthsInRange($startDate, $endDate)
{
    $months = array();

    while (strtotime($startDate) <= strtotime($endDate)) {
        $months[] = array(
            'year' => date('Y', strtotime($startDate)),
            'month' => date('m', strtotime($startDate)),
        );

        // Set date to 1 so that new month is returned as the month changes.
        $startDate = date('01 M Y', strtotime($startDate . '+ 1 month'));
    }

    return $months;
}
于 2015-08-13T03:24:32.833 回答
5

这是我的解决方案,因为 DateTime 在我的服务器环境中不可用。

$a = "2007-01-01";
$b = "2008-02-15";

$i = date("Ym", strtotime($a));
while($i <= date("Ym", strtotime($b))){
    echo $i."\n";
    if(substr($i, 4, 2) == "12")
        $i = (date("Y", strtotime($i."01")) + 1)."01";
    else
        $i++;
}

试试看:http: //3v4l.org/BZOmb

于 2015-01-26T13:06:31.883 回答
2

在 Laravel 中,

$period = \Carbon\CarbonPeriod::create('2017-06-28', '1 month', '2019-06-01');

foreach ($period as $dt) {
     echo $dt->format("Y-m") . "<br>\n";
}
于 2020-08-31T16:22:15.793 回答
0

2021 年 10 月更新
如果您有用户选择的日期,这里有一个解决方案

$from = date('Y-m-d', strtotime($_POST['from']));
$to = date('Y-m-d', strtotime($_POST['to']));

$counter = 1;
$max_date = strtotime($to);
$current_date = strtotime($from);
$dates = [];
$months = [];
$loop = true;
while($loop) {
    if(strtotime(date('Y-m-d',$current_date)." +".$counter."days") >= $max_date) $loop = false;
    else {
        $current_date = strtotime(date('Y-m-d', $current_date)." +".$counter."days");
        $date = date('Y-m-d', $current_date);
        $dates[] = $date;
        $months[] = date('Y-m', $current_date);
        $counter++;
    }
}
$months = array_unique($months);
echo '<pre>';
print_r($dates);
echo '<br>';
print_r($months);
echo '</pre>';
于 2021-10-16T01:38:28.090 回答