Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get the number of the month before of the current month

Tags:

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.

like image 622
ziiweb Avatar asked Apr 20 '11 16:04

ziiweb


People also ask

How can I get current month number?

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.

How do you get the first Date of the month in typescript?

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.


2 Answers

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.

like image 178
glebtv Avatar answered Sep 26 '22 00:09

glebtv


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;
like image 29
GordyB Avatar answered Sep 25 '22 00:09

GordyB