当DateTime在31个月结束时调用时,会发生月份重复

时间:2017-05-31 22:17:18

标签: php date

当我在5月的最后一天(31日)运行以下内容时,我发生了一些奇怪的行为。如果我将系统时间更改为5月30日或6月(30日)的最后一天,它将正常运行。

出于某种原因,在31日,它将跳过下个月(6月),而是将其替换为7月。因此它将在7月两次输出。这是一个例子:

31 days in 05, 31 days in 07, 31 days in 07, 31 days in 08,

生成上述代码的代码

<?php
$datepicker_month_range = 3;

// create an array of dates for a number of months specified by the user. 0 is used for this month
for ($month = 0; $month <= $datepicker_month_range; $month++) {
  $dt_dates = new DateTime();
  $dt_dates->add(new DateInterval("P{$month}M")); // example, P1M == plus 1 month
  $days_in_month = cal_days_in_month(CAL_GREGORIAN, $dt_dates->format('m'), $dt_dates->format('Y'));

  echo $days_in_month." days in ".$dt_dates->format('m').", ";

  for ($day = 1; $day <= $days_in_month; $day++) {
    $date = $dt_dates->format('Y')."-".$dt_dates->format('m')."-".sprintf('%02d', $day); // leading zeros 05-..
    $month_days[] = $date; 
  }
}
//print_r($month_days);
?>

稍后,如果运行print_r($month_days),则输出完整日期,并在7月输出两次,就像前一个表达式一样。

导致此行为的原因是什么?

感谢。

1 个答案:

答案 0 :(得分:0)

好的,看完评论后,似乎这是PHP DateTime::modify adding and subtracting months

的副本

但这是我解决问题的方法。

$month_beginning = $dt_dates->format('Y-m-01');
$dt_dates = new DateTime($month_beginning); // rollback the date to the first so we can increment months safely

一起

for ($month = 0; $month <= $datepicker_month_range; $month++) {
  $dt_dates = new DateTime();
  $month_beginning = $dt_dates->format('Y-m-01');
  $dt_dates = new DateTime($month_beginning); // rollback the date to the first so we can increment months safely
  $dt_dates->add(new DateInterval("P{$month}M")); // P1M == plus 1 month
  $days_in_month = cal_days_in_month(CAL_GREGORIAN, $dt_dates->format('m'), $dt_dates->format('Y'));
  //echo $days_in_month." days in ".$dt_dates->format('m').", ";
  for ($day = 1; $day <= $days_in_month; $day++) {
    $date = $dt_dates->format('Y')."-".$dt_dates->format('m')."-".sprintf('%02d', $day); // leading zeros 05-..
    $month_days[] = $date; // holds dates for datepicker month ranges
  }
}