Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP strtotime: Get previous month [duplicate]

Possible Duplicate:
How to get previous month and year relative to today, using strtotime and date?

Today is December, 31st but strtotime("-1 months") returns December:

echo date("Y-m", strtotime("-1 months"));

Same for strtotime("last month")

How can I properly return the previous month (November)?

Test: http://codepad.viper-7.com/XvMaMB

like image 811
Martin Avatar asked Dec 31 '12 14:12

Martin


2 Answers

strtotime("first day of last month")

The first day of is the important part as detailed on the Relative Formats manual page.


Example: http://codepad.viper-7.com/dB35q8 (with hard-coded today's date)

like image 77
salathe Avatar answered Nov 03 '22 04:11

salathe


strtotime("-1 months") would be 2012-11-31, but there's no November, 31st. It is one day past 2012-11-30, which gives 2012-12-01. You will see it, when you do

echo date("Y-m-d", strtotime("-1 months"));

gives as output

2012-12-01

See codepad

like image 36
Olaf Dietsche Avatar answered Nov 03 '22 02:11

Olaf Dietsche