获取两年之间的年份清单?

时间:2017-03-20 15:24:40

标签: php datetime

我有这个方法:

public function getYears($startYear = 1990, $endYear = date ('Y')){
    $years = [];
    $date = new \DateTime();

    $years[$date->format('Y')] = $date->format('Y'); 
    while ($endYear <= $startYear){
       $date->add(new \DateInterval('P1Y'));
       $years[$date->format('Y')] = $date->format('Y');
       $endYear++;
    }
   return $years;
}

这段代码不起作用,但你明白我想要的是什么?我怎样才能做到这一点? THX

2 个答案:

答案 0 :(得分:4)

如果我理解你的问题,这很容易:

$arYears = range(1990, date('Y'));

答案 1 :(得分:1)

如果你想坚持循环,你可以这样做:

function getYears($startYear = 1990, $endYear = date ('Y')) {
  $years = [];
  for ($y = $startYear; $y < $endYear; $y++) {
    $years[] = $y;
  }
  return $years;
}