Abubakkar
Abubakkar

Reputation: 15654

How to subtract more than 1 month in PHP variable having only month part?

I am in little trouble.

I am two variable for current month and previous month:

I only want month part

so this what I have written:

$current_month = date('F');
$previous_month = date('F', strtotime($current_month.' -1 F'));

when doing echo it prints :

May April

Now this works perfectly for 1 month.

But when I change the value of -1 to something else say -3, it always has May as the value.

it prints May - May

I have checked it with -3 months but it doesn't work.

Also I have seen in docs how to subtract months from date, but they involve whole date object, I only need months.

Upvotes: 1

Views: 1170

Answers (2)

Fabio
Fabio

Reputation: 23490

Try this

$current_month = date('F');

$previous_month = date('F', strtotime('-3 months'));

echo $previous_month;

This will output

February

LIVE DEMO

Upvotes: 1

xdazz
xdazz

Reputation: 160843

-3 month works perfectly.

$current_month = date('F');
$previous_month = date('F', strtotime('-3 month'));
$previous_month = date('F', strtotime('3 month ago')); // also works

The demo.

Upvotes: 1

Related Questions