月份和年份在 PHP 中不起作用

Month and Year not working in PHP

我想获取接下来 18 个月的月份和年份。 我试过以下代码:

$dat=strtotime(date('Y-m-d'));
  $mnth = date('n');
  $yr=date('Y');
  echo $mnth." | " . $yr . " | " . date("Y-m-d", $dat);
  echo "<hr>";
  for($i=0; $i<=18;$i++)
  {
    echo date("n", strtotime("+1 month", $dat)) ." | ".date("Y", strtotime("+1 month", $dat)) . " | " . date("Y-m-d", strtotime("+1 month", $dat)) ."<br><hr>";
    $dat=date("Y-m-d", strtotime("+1 month", $dat));
  }

迭代和第一次迭代之前的代码工作正常,如下所示:

8 | 2018 | 2018-08-28  
9 | 2018 | 2018-09-28

但所有后续迭代都出现以下错误:

Notice: A non well formed numeric value encountered in D:\Programs\PHP\aa\tdate.php on line 11

Notice: A non well formed numeric value encountered in D:\Programs\PHP\aa\tdate.php on line 11

Notice: A non well formed numeric value encountered in D:\Programs\PHP\aa\tdate.php on line 11 2 | 1970 | 1970-02-01

请提出一些解决方案。

当您尝试使用 date()strtotime() 来操纵日期时,您正在以它们并非真正设计的方式使用它们。

使用 DateTime() with DateInterval() and DatePeriod() 可以让您快速、轻松地 清楚地.

遍历日期
$start     = new \DateTime('first day of this month');
$end       = (new \DateTime('first day of this month'))->modify('+18 months'); 
$interval  = new \DateInterval('P1M');
$period    = new \DatePeriod($start, $interval, $end);
foreach ($period as $month) {
    $lastDayOfMonth = $month->format('t');
    $day = (date('d') > $lastDayOfMonth) ? $lastDayOfMonth : date('d');
    echo $month->format("n | Y | Y-m-{$day}");
    echo "\n";
}

Demo

一些注意事项:

  1. 确保你的开始日期是每月的第一天,就好像你使用的代码有 31 天的月份,它会中断,而 2 月从每个月的 29 日到月底都是一个问题那个月。
  2. 如果当前日期在另一个月的最后一天之后,您需要返回到该月的最后一天。这将从 29 日起每月有 31 天的月份和二月发挥作用。

我建议使用 DateTime class 来完成这个,这样会容易得多:

// The actual month
$date = new DateTime(date('Y-m-') . '1');

// For the next 18 months
for ($i=0; $i < 18; $i++) {

    // Add a month to the date
    $date->add(new DateInterval('P1M'));

    // Output it as you wish:
    echo $date->format('n | Y | Y-m-d') . '<br>';
}

$dat=strtotime(date('Y-m-d'));
for($i=0; $i<=18;$i++)
{
    echo date("n", strtotime("+".$i." month", $dat)) ." | ".date("Y", strtotime("+".$i." month", $dat)) . " | " . date("Y-m-d", strtotime("+".$i." month", $dat)) ."<br><hr>";
}