I'm trying to get the number of month before of the current month (now is 04
(april), so I'm trying to get 03
). I'm trying this:
date('m')-1;
but I get 3
. But what I want is to get 03
.
Use the new Date() constructor to get a date object. Call the getMonth() method on the object and add 1 to the result. The getMonth method returns a zero-based month index so adding 1 returns the current month.
To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates. Copied! const now = new Date(); const firstDay = new Date(now. getFullYear(), now.
The correct way to do this really is:
date('m', strtotime('-1 month'));
As you will see strange things happen in January with other answers.
The currently accepted response will result in an incorrect answer whenever the day of the month (for the current day) is a larger number than the last day of the month for the previous month.
e.g. The result of executing date('m', strtotime('-1 month'));
on March 29th (in a non-leap-year) will be 03, because 29 is larger than any day of the month for February, and thus strtotime('-1 month')
will actually return March 1st.
Instead, use the following:
date('n') - 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With