dougong2306 2014-03-29 18:27
浏览 31
已采纳

显示当前日期过去11个月的列表

I am drawing a bar graph and the values on the x-axis are the months in the last one year period. For example, this is March 2014; so the values on the x-axis range from April 2013 to March 2014 which is the current month.

I am using echo date('M'); to print the current month and echo date('M', strtotime(' -1 month')); and echo date('M', strtotime(' -2 month')); and so on to get all previous months.

These have been working fine until today, 29th March.

Where 'Feb' is supposed to be is also printing 'Mar'. I figure it is because February has 28 days.

Is there an easy fix to this without having to use if... else statements or if... else shorthand statements on all echo statements telling it to echo date('M', strtotime('-n month 2 days')); ?

  • 写回答

2条回答 默认 最新

  • douyicao2199 2014-03-29 18:33
    关注

    This is due to how PHP handles date math. You need to make sure you are always working with the first of the month to ensure February does not get skipped.

    DateTime(), DateInterval(), and DatePeriod() makes this really easy to do:

    $start    = new DateTime('11 months ago');
    // So you don't skip February if today is day the 29th, 30th, or 31st
    $start->modify('first day of this month'); 
    $end      = new DateTime();
    $interval = new DateInterval('P1M');
    $period   = new DatePeriod($start, $interval, $end);
    foreach ($period as $dt) {
        echo $dt->format('F Y') . "<br>";
    }
    

    See it in action

    You can obviously change $dt->format('F Y') to $dt->format('M') to suit your specific purposes. I displayed the month and year to demonstrate how this worked.

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

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)