未来12个月和过去12个月

时间:2014-01-13 10:50:42

标签: php date

我如何在过去的12个月以及未来的12个月中循环使用。

i imainge最简单的方法就是在过去的24个月里开始一年的开始,例如2015年1月

我目前的代码返回过去12个月

for ($i = 1; $i <= 12; $i++) {
$my = date("F Y", strtotime( date( 'Y-m-01' )." -$i months"));
$ymd = date("Y-m-d", strtotime( date( 'Y-m-01' )." -$i months"));

4 个答案:

答案 0 :(得分:3)

这可以通过DateTime扩展名来完成:

$months = 12; # number of months before and after current month
$dt = new DateTime('first day of this month'); # select first day in current month
$dt->modify("-$months month");
for ($i = 0; $i <= $months * 2; $i++) {
    echo $dt->format('M Y'), "\n";
    $dt->modify('+1 month');
}

demo

答案 1 :(得分:0)

试试这个

for ($i = 1; $i <= 12; $i++) 
{
$my = date("F Y", strtotime( date( 'Y-m-01' )." -$i months"));
$ymd = date("Y-m-d", strtotime( date( 'Y-m-01' )." -$i months"));

$f_my = date("F Y", strtotime( date( 'Y-m-01' )." +$i months"));
$f_ymd = date("Y-m-d", strtotime( date( 'Y-m-01' )." +$i months"));

}

答案 2 :(得分:0)

$arrPast = array();
$arrFut  = array();
for ($i = 1; $i <= 12; $i++) {
    $arrPast[]  = date("Y-m-d", strtotime( date( 'Y-m-d' )." -$i months"));
    $arrFut[]   = date("Y-m-d", strtotime( date( 'Y-m-01' )." +$i months"));
}

echo 'Past 12 months <pre>';
print_r($arrPast);

echo 'Future 12 months <pre>';
print_r($arrFut);

答案 3 :(得分:0)

应该是

$pastDate = date("Y-m-d", strtotime( date( 'Y-m-01' )." -12 months"));

$futureDate = date("Y-m-d", strtotime( date( 'Y-m-01' )." +12 months"));

for ($i = $pastDate; $i <= $futureDate; $i = date("Y-m-d", strtotime($i." +1 months")))
{
    echo "<br />Current Month(Y-m-d) is ".$i;
}
相关问题