How to get the last day of the previous month in Javascript or JQuery

This works perfectly for me:

var date = new Date();
date.setDate(0);

date now contains the last day of the previous month.


var d=new Date(); // current date
d.setDate(1); // going to 1st of the month
d.setHours(-1); // going to last hour before this date even started.

now d contains the last date of the previous month. d.getMonth() and d.getDate() will reflect it.

This should work on any date api that wraps c time.h.


From the answers I was get most of them were failing to capture 31 in the May so I tried out several options and these are the ones I came up with. Hope, some may find this useful.

const today = new Date()
const lastMonth = today.getMonth() === 0 ? 11 : today.getMonth() - 1
const year = lastMonth === 0 ? today.getFullYear - 1 : today.getFullYear

const lastDayOfLastMonth = new Date(year, lastMonth + 1, 0).getDate()
const lastDateTimeOfLastMonth = new Date(year, lastMonth + 1, 1)
const lastDateOfLastMonth = new Date(year, lastMonth + 1, 0).toLocaleDateString()

console.log(lastDayOfLastMonth) // eg 31
console.log(lastDateTimeOfLastMonth) // eg 2021-05-31T16:00:00.000Z
console.log(lastDateOfLastMonth) // eg 31/05/2021

var lastdayoflastmonth = new Date();
lastdayoflastmonth.setMonth(lastdayoflastmonth.getMonth(), 0);
var firstdayoflastmonth = new Date();
firstdayoflastmonth.setDate(1);
firstdayoflastmonth.setMonth(firstdayoflastmonth.getMonth()-1);