get last 3 months from current month using php

后端 未结 4 1040
[愿得一人]
[愿得一人] 2021-01-27 19:58

I want to get last 3 months name from current month. For example current month is August. So, I want the datas like these June, July, August. I have tried this code echo d

相关标签:
4条回答
  • 2021-01-27 20:51

    That should work:

    function lastThreeMonths() {
        return array(
            date('F', time()),
            date('F', strtotime('-1 month')),
            date('F', strtotime('-2 month'))
        );
    }
    
    var_dump(lastThreeMonths());
    
    0 讨论(0)
  • 2021-01-27 20:53

    You are actually on the right track by using date and strtotime functions. Expanding it below to your requirements:

    function getMonthStr($offset)
    {
        return date("F", strtotime("$offset months"));
    }
    
    $months = array_map('getMonthStr', range(-3,-1));
    
    0 讨论(0)
  • 2021-01-27 20:55

    Try this:-

    $current_date = date('F');
    for($i=1;$i<3;$i++)
    {
        ${"prev_mont" . $i} = date('F',strtotime("-$i Months"));
        echo ${"prev_mont" . $i}."</br>";
    }
    echo $current_date."</br>";
    
    0 讨论(0)
  • 2021-01-27 21:02

    Simple code:

    <?php
    
    for($x=2; $x>=0;$x--){
    echo date('F', strtotime(date('Y-m')." -" . $x . " month"));
    echo "<br>";
    }
    
    ?>
    

    Got the idea from LTroubs here.

    0 讨论(0)
提交回复
热议问题