Get the first and last date of the previous month in JQuery
That's the first day of the current month new Date(now.getFullYear(), now.getMonth(), 1)
to get the last day of the previous month create a date 1-day earlier: new Date(now.getFullYear(), now.getMonth(), 1 - 1)
.
To get the first day of the previous month we should substract 1 from the month component new Date(now.getFullYear(), now.getMonth() - 1, 1)
but there is an issue if the current month is January (0) and the previous month is December (11). Hence I wrapped the month expression creating a cycle so it always returns a positiove value.
var now = new Date();
var prevMonthLastDate = new Date(now.getFullYear(), now.getMonth(), 0);
var prevMonthFirstDate = new Date(now.getFullYear() - (now.getMonth() > 0 ? 0 : 1), (now.getMonth() - 1 + 12) % 12, 1);
var formatDateComponent = function(dateComponent) {
return (dateComponent < 10 ? '0' : '') + dateComponent;
};
var formatDate = function(date) {
return formatDateComponent(date.getMonth() + 1) + '/' + formatDateComponent(date.getDate()) + '/' + date.getFullYear();
};
document.write(formatDate(prevMonthFirstDate) + ' - ' + formatDate(prevMonthLastDate));
You can do it like this
//one day previous Date
var date = new Date();
date.setDate(date.getDate() - 1);
console.log(date.getDay());
//for previous month last date
var date = new Date();
date.setDate(0);
console.log(date);
//for perivous Month First date
var date = new Date();
date.setDate(0);
date.setDate(1);
console.log(date);
Try using bellow
var date = new Date();
var monthStartDay = new Date(date.getFullYear(), date.getMonth(), 1);
var monthEndDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);