dscdttg4389 2011-10-10 04:25
浏览 51
已采纳

如何使用循环使用PHP以yyyy_mm格式列出日期?

What's the cleanest way to use a loop in PHP to list dates in the following way?

2011_10
2011_09
2011_08
2011_07
2011_06
...
2010_03
2009_02
2009_01
2009_12
2009_11

The key elements here:

  • Should be as simple as possible - I would prefer one for loop instead of two.
  • Should list this month's date as the first date, and should stop at a fixed point (2009-11)
  • Should not break in the future (eg: subtracting 30 days worth of seconds will probably work but will eventually break as there are not an exact amount of seconds on each month)

Had to make a few tweaks to the solution:

    // Set timezone
    date_default_timezone_set('UTC');

    // Start date
    $date = date('Y').'-'.date('m').'-01';
    // End date
    $end_date = '2009-1-1';

    while (strtotime($date) >= strtotime($end_date))
    {
        $date = date ("Y-m-d", strtotime("-1 month", strtotime($date)));
        echo substr($date,0,7);
        echo "
";
    }
  • 写回答

3条回答 默认 最新

  • download2565 2011-10-10 04:30
    关注

    Maybe this little code does the thing? : more complicated situations.

        <?php
            // Set timezone
            date_default_timezone_set('UTC');
    
            // Start date
            $date = '2009-12-06';
            // End date
            $end_date = '2020-12-31';
    
            while (strtotime($date) <= strtotime($end_date)) {
                echo "$date
    ";
                $date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
            }
    
     ?>
    

    The credit goes to: http://www.if-not-true-then-false.com/2009/php-loop-through-dates-from-date-to-date-with-strtotime-function/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波