Karuppiah RK
Karuppiah RK

Reputation: 3964

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?

Upvotes: 0

Views: 4917

Answers (4)

Kavita
Kavita

Reputation: 79

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

Upvotes: 0

coder.in.me
coder.in.me

Reputation: 1068

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

Upvotes: 4

laurent
laurent

Reputation: 90794

That should work:

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

var_dump(lastThreeMonths());

Upvotes: 3

kimbarcelona
kimbarcelona

Reputation: 1136

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.

Upvotes: 4

Related Questions