拆分为月份和年份变量

时间:2017-07-03 23:30:56

标签: php date

我有这段代码,将从2016年到2017年生成月份和年份。

如何简化此代码并将其分为两个月和一年的变量?

$start = $month = strtotime('2016-01-01');
$end = strtotime('2017-12-31');
while($month <=$end)
{
     echo date('F Y', $month), PHP_EOL;
     echo "<br />";
     $month = strtotime("+1 month", $month);
}

2 个答案:

答案 0 :(得分:2)

只需拨打date()两次。一年一次,一个月一次。

$start = $month = strtotime('2016-01-01');
$end = strtotime('2017-12-31');
while($month <=$end)
{
     echo date('F', $month), ' ', date('Y', $month), PHP_EOL;
     echo "<br />";
     $month = strtotime("+1 month", $month);
}

显然,您可以更改格式以满足您的需求。

答案 1 :(得分:1)

热爱Datetime,我会这样做:

<?php
  $date = new DateTime('2016-01-01');
  $enddate = new DateTime('2017-12-31');
  while($date < $enddate) {
    $month = $date->format('m');
    $year = $date->format('Y');
    echo $year .' '. $month . '<br>'.PHP_EOL;
    $date->modify('+1 Month');
  }
相关问题