php - 为每年的每个月循环

时间:2013-08-08 09:29:21

标签: php date loops for-loop

我想要一个循环来检查当前月份,未来12个月和过去4个月。

例如:今天是08年8月1日。我的循环应该经历四月,五月,六月,七月,八月,九月,十月,十一月,十二月,一月,二月,三月,四月,五月,六月,七月,八月。

我已尝试过strotime,但我不知道如何在4个月前和未来12个月内循环。

这是我的代码

$i = 1; 
$month = strtotime('2013-08-01');

    while($i <= 12) {
        $month_name = date('F', $month);
        echo $month_name;
        echo "<br>";

        $month = strtotime('+1 month', $month);
        $i++;

6 个答案:

答案 0 :(得分:3)

我认为Yoshi几乎与his answer在一起,但使用DatePeriodDateTime更加一致并且使代码更具可读性恕我直言: -

$oneMonth = new \DateInterval('P1M');
$startDate = \DateTime::createFromFormat('d H:i:s', '1 00:00:00')->sub(new \DateInterval('P4M'));
$period = new \DatePeriod($startDate, $oneMonth, 16);

foreach($period as $date){
    //$date is an instance of \DateTime. I'm just var_dumping it for illustration
    var_dump($date);
}

See it working

答案 1 :(得分:2)

这可能非常棘手,我要这样做:

$month = date("n", "2013-08-01") - 1; // -1 to get 0-11 so we can do modulo

// since you want to go back 4 you can't just do $month - 4, use module trick:
$start_month = $month + 8 % 12;
// +8 % 12 is the same is -4 but without negative value issues
// 2 gives you: 2+8%12 = 10 and not -2

for ($i = 0; $i < 16; $i += 1) {
    $cur_month = ($start_month + $i) % 12 + 1; // +1 to get 1-12 range back
    $month_name = date('F Y', strtotime($cur_month . " months"));
    var_dump(month_name);
}

答案 2 :(得分:1)

这样的事情?:

$start = -4;
$end = 12;

for($i=$start; $i<=$end;$i++) {
    $month_name = date('F Y', strtotime("$i months"));
    echo $month_name;
    echo "<br>";
}

答案 3 :(得分:1)

最简单的解决方案:

for($i=-4; $i<=12; $i++) {
    echo date("F",strtotime( ($i > 0) ? "+$i months" : "$i months") )."\n";
}

说明:

循环从-4开始,一直到12(总共17,包括0)。 strtotime()中的三元语句只是检查$ i是否为正数,如果是,则插入+,以便我们得到strtotime("+1 months")和类似的结果。

Ta-da!

答案 4 :(得分:1)

您的代码,稍加修改。

date_default_timezone_set('UTC');

$i = 1;
$month = strtotime('-4 month');

while($i <= 16) {
    $month_name = date('F', $month);
    echo $month_name;
    echo "<br>";

    $month = strtotime('+1 month', $month);
    $i++;
}

答案 5 :(得分:0)

使用DateTime是最简单,更易读的方式。 我会这样做:

$from = new DateTime('-4 month');
$to   = new DateTime('+12 month');
while($from < $to){
  echo $from->modify('+1 month')->format('F');
}
相关问题