2017-07-03 118 views
1

我有这样的代码,将生成月份和年份从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

只需拨打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); 
} 

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

+0

谢谢你的答案 – gtroop

1

具有日期时间的热爱,我会做:

<?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'); 
    } 
+0

谢谢你的答案 – gtroop