php for-loop中的自定义月份和年份

时间:2018-08-08 09:43:26

标签: php datetime for-loop

我看到了这个问题: how to get the previous 3 months in php

我的问题是..如何从自定义月份输出。
我想从//subscribe to idle message this.authService.idleSubject.subscribe( (msg: string) => { this.ngZone.run(() => { this.idleWarningMsg = msg; this.isIdleMsg = msg != null && msg != ''; //console.log("=> [" + this.idleWarningMsg + '::' + this.isIdleMsg + "]") }); } ); (或任何Mar 2018个用户输入)开始,它应该输出接下来的M Y(或任何数量的用户输入)个月。
例如:3MarApr

下面的代码来自当前月份和年份。

May

输出为

// current month: Aug 2018
for ($i = 0; $i <= 2; $i++){
    $x = strtotime("$i month");
    echo $dte = date('M Y', $x);
    echo '<br>';
}

6 个答案:

答案 0 :(得分:3)

您可以使用DateTime类,并使用DateInterval对象递增:

// Assuming these are the user inputs
$month = 11;
$year = 2015;

// We create a new object with year and month format
$date = DateTime::createFromFormat('Y m', $year . ' ' . $month);


for ($i = 0; $i <= 2; $i++){
    // Output the month and year
    echo $date->format('m Y') . '<br>';

    // Add 1 month to the date
    $date->add(new DateInterval('P1M'));
}

输出:

  

11 2015
  2015年12月12日
  2016年1月1日

文档:

答案 1 :(得分:2)

将其更改为如下所示,它将为您提供预期的效果,请参见以下代码

    // current month: Aug 2018
  $effective_date = "MAR 2018";
for ($i = 0; $i <= 2; $i++){
    $x = strtotime("$i month",strtotime($effective_date));
    echo $dte = date('M Y', $x);
    echo '<br>';
}

答案 2 :(得分:1)

这可能也有帮助:

<?php
$month = 11;
$year  = 2017;
$count = 15;

for ($i = 1; $i <= $count; $i++) {
    $month++;
    if ($month > 12) {
        $month = 1;
        $year++;    
    }   
    $x = DateTime::createFromFormat('Y-m', $year.'-'.$month);
    echo $x->format('m-Y');
    echo '<br>';
}
?> 

输出:

12-2017
01-2018
02-2018
03-2018
04-2018
05-2018
06-2018
07-2018
08-2018
09-2018
10-2018
11-2018
12-2018
01-2019
02-2019

答案 3 :(得分:0)

尝试使用此代码添加第n天,月和年

$n = 2;
for ($i = 0; $i <= $n; $i++){
    $d = strtotime("$i days");
    $x = strtotime("$i month");
    $y = strtotime("$i year");
    echo "Dates : ".$dates = date('d M Y', "+$d days");
    echo "<br>";
    echo "Months : ".$months = date('M Y', "+$x months");
    echo '<br>';
    echo "Years : ".$years = date('Y', "+$y years");
    echo '<br>';
}

答案 4 :(得分:0)

您可以使用strtotime()函数生成日期

选中此phpfiddle

127.0.0.1       www.ciadmin.local
127.0.0.1       www.ci_login.local

答案 5 :(得分:-1)

<?php

$year = date('Y');

//start at march 
$startMonth = 7;

//go forwards 2 months
$stepForwards = 22;    

for ($i = $startMonth; $i <= $stepForwards; $i++){

    if($i > 12 ) {

        $month = $i % 12 == 0 ?  12 : $i % 12;

    }
    else {

       $month = $i;

    }

    echo date("M Y", strtotime(date($year.'-'.$month.'-1'))) . "<br/>";

    if($month == 12) {

        $year++;

        echo "<br/>";

    }

}
相关问题