简体   繁体   中英

get last 3 months from current month using php

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 date("F", strtotime("-3 months")); . it returns June only. How do I get last 3 months from current month using php?

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 .

That should work:

function lastThreeMonths() {
    return array(
        date('F', time()),
        date('F', strtotime('-1 month')),
        date('F', strtotime('-2 month'))
    );
}

var_dump(lastThreeMonths());

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));

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>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM