PHP strtotime: Get previous month [duplicate]
Asked Answered
H

2

23

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

Hendrix answered 31/12, 2012 at 14:14 Comment(0)
R
38
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)

Rendarender answered 31/12, 2012 at 14:17 Comment(6)
Thanks. Very misleading! Sounds like it would return "1" or the weekday.Hendrix
@Hendrix Try it and find outEncephalograph
@Martin: strtotime always returns a timestamp (or false on failure). So it will return a timestamp of the first day of the last month, but since you are outputting it in Y-m format, that's fine for you.Doorkeeper
"first day of next month" doesn't work in PHP 5.2.4Hendrix
Lots of things won't work in ancient versions of the language.Rendarender
What will happen if the date is something like 2014-01-31 will it return 2013-12-01..?Branny
B
11

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

Bactria answered 31/12, 2012 at 14:26 Comment(1)
Thanks, that explains it.Hendrix

© 2022 - 2024 — McMap. All rights reserved.