user3541631
user3541631

Reputation: 4008

Getting the last day of previous/last month in javascript

I'm using the following code, where month is the current month(where am I):

 lastDayOfLastMonth = month === 0 ? new Date(year - 1, 11, 0).getDate() : new Date(year, month, 0).getDate();

the idea, is if I'm on the first month of an year, the previous month is the last month of the previous year.

If I'm on January 2018, is reporting that December 2017 last day was 30, which is not true, it was 31, but I don't figure why.

Upvotes: 2

Views: 227

Answers (4)

Fancy5g
Fancy5g

Reputation: 109

Try this instead:

lastDayOfLastMonth = month === 0 ? new Date(year - 1, 12, 0).getDate(): 
                                   new Date(year, month, 0).getDate();

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176956

below also give you result you want

var LastDay =  new Date(year-1, 12, 0);
//new Date(year - 1, 11, 0).getDate() this line seems issue in your code

this one returns december 31 2017 for me

 var month = 0;//this you will get when do dt.getMonth() in January month
 var year = 2018;           
 var LastDay = new Date(year, month, 0);

document.getElementById("demo").innerHTML = LastDay;

try this out its working for me

 var dt = new Date();
 var month = dt.getMonth();
 var year = 2018;

 var LastDay = new Date(year, month, 0);

 console.log(LastDay);

Upvotes: 0

tylerwgrass
tylerwgrass

Reputation: 656

The day part of the Date constructor is not 0-indexed, but the actual day of the month. In your first condition, new Date(year - 1, 11, 0).getDate(), you will first initialize your date to be December 0, 2017. The date constructor then corrects this as November 30, 2017.

If you want the last day of the previous month, you can ignore the ternary operator and do the following, as the Date constructor will make the necessary conversions:

lastDayOfLastMonth = new Date(currentYear, currentMonth, 0).getDate();

Note that currentMonth is still 0-indexed (i.e. January is month 0 and December is month 11)

Upvotes: 1

Max Ferreira
Max Ferreira

Reputation: 719

var d = new Date();
var n = d.getMonth();
// first month
if(n == 0){
    console.log(new Date(new Date().getFullYear(), 11, 31).getDate());
}

Upvotes: 0

Related Questions