循环年月

时间:2018-11-02 17:33:05

标签: php

如何在给定日期的年份和月份中循环显示? 下面是我当前的代码,我无法运行

$Startdate = '2017-01';
$Enddate = '2018-06';

 for($selectedDate = date("Y-m",$begin); $selectedDate <= date("Y-m",$end); $selectedDate++){
    $resultY = date("Y",strtotime($selectedDate));
    $resultM = date("m",strtotime($selectedDate));

    echo $resultY;
    $echo resulthM;
}

输出应为:

2017    1
2017    2
2017    3
2017    4
2017    5
2017    6
2017    7
2017    8
2017    9
2017    10
2017    11
2017    12
2018    1
2018    2
2018    3
2018    4
2018    5
2018    6

4 个答案:

答案 0 :(得分:5)

如果我是您 :),我将尝试使用DateTime类在您的$Startdate$Enddate之间产生几个月。参见DateTime

<?php
 $start    = new DateTime('2017-01');
 $end      = new DateTime('2018-06');
 $interval = DateInterval::createFromDateString('1 month');
 $period   = new DatePeriod($start, $interval, $end);
 foreach ($period as $dt) {
    echo $dt->format("Y-m") . PHP_EOL;
 }

演示: https://3v4l.org/FvmS4

答案 1 :(得分:0)

$startDate = new \DateTime('2017-01-01'); 
$endDate = new \DateTime('2018-06-01');

for($selectedDate = $startDate; $selectedDate <= $endDate; $selectedDate->modify('+1 month')) {
    // format $selectedDate;
    $resultY = $selectedDate->format('Y');
    $resultM = $selectedDate->format('m');

    // print content
    echo $resultY;
    echo "\t";  // print tab
    echo $resultM;
    echo "\n";  // print new line
}

答案 2 :(得分:0)

由于您熟悉strtotime,因此可以将代码修改为以下内容以执行所需的结果。

$begin = date("Y-m", strtotime("2017-01")); // Replace this with date to begin.
$end = date("Y-m"); // Replace this with date to end.

for($selectedDate = date("Y-m", strtotime($begin)); $selectedDate <= date("Y-m", strtotime($end)); $selectedDate = date("Y-m", strtotime($selectedDate . "+1 Month"))){
    $resultY = date("Y", strtotime($selectedDate));
    $resultM = date("m", strtotime($selectedDate));

    echo $resultY;
    echo $resultM;
}

但是,同样,用户也不要生气,我给出的答案将允许您使用DateTime对象并对其进行操作,因此,如果您希望将代码切换到可能更可靠的方式,则可以

答案 3 :(得分:0)

您可以使用DateTime::modify并向前走几个月

$Startdate = '2017-01';
$Enddate = '2018-06';

$DateTime = new DateTime($Startdate.'-01');

echo $DateTime->format('Y')."\t".$DateTime->format('n')."\n";

do{
   $DateTime->modify('+1 months');

   echo $DateTime->format('Y')."\t".$DateTime->format('n')."\n";

   if($DateTime->format('Y-m') == $Enddate) break;

}while(true);

只需确保Enddate是有效的年/月并且在Startdate之后发生,否则在此示例中,您将永远循环播放。

可能还有其他方法可以避免这种情况。

但是我没有在答案中使用DateTime::modify,所以我想我会把它们放在一起。

输出:

2017    1
2017    2
2017    3
2017    4
2017    5
2017    6
2017    7
2017    8
2017    9
2017    10
2017    11
2017    12
2018    1
2018    2
2018    3
2018    4
2018    5
2018    6

Sandbox

当我想对诸如月之类的东西进行选择/选择时,我通常使用这种方法。但是我使用str_pad($DateTime->format('n'),2,' ',STR_PAD_LEFT).' - '.$DateTime->format('F')' 2 - February'这种格式,请注意左侧的空格... :) ...这样,它们都排列整齐美观。

反正加油!

相关问题