Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the previous month's first date from current date in JavaScript

Tags:

javascript

People also ask

How do you get the first date of the month from a date in JavaScript?

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.

How can I get previous month in moment?

To get the previous month in moment js, use the subtract(1, "month") method to subtract the month in date and use format('MMMM') to get the month name from subtracted date. Just import moment in your file and call moment(). subtract(1, "month"). format('MMMM') and it will return previous month.


Straightforward enough, with the date methods:

  var x = new Date();
  x.setDate(1);
  x.setMonth(x.getMonth()-1);

Simplest way would be:

var x = new Date();
x.setDate(0); // 0 will result in the last day of the previous month
x.setDate(1); // 1 will result in the first day of the month

Deals with updating year when moving from January to December

var prevMonth = function(dateObj) {
	var tempDateObj = new Date(dateObj);

	if(tempDateObj.getMonth) {
		tempDateObj.setMonth(tempDateObj.getMonth() - 1);
	} else {
		tempDateObj.setYear(tempDateObj.getYear() - 1);
		tempDateObj.setMonth(12);
	}

	return tempDateObj
};

var wrapper = document.getElementById('wrapper');

for(var i = 0; i < 12; i++) {
	var x = new Date();
  var prevDate = prevMonth(x.setMonth(i));
	var div = document.createElement('div');
  div.textContent = 
  "start month/year: " + i + "/" + x.getFullYear() +
  " --- prev month/year: " + prevDate.getMonth() +
  "/" + prevDate.getFullYear() +
  " --- locale prev date: " + prevDate.toLocaleDateString();
  wrapper.appendChild(div);
}
<div id='wrapper'>
</div>

This worked for me

var curDateMonth = new Date();
var prvDateMonth = new Date(curDateMonth.getFullYear(),curDateMonth.getMonth()-1,curDateMonth.getMonth());
console.log(curDateMonth.toLocaleString('en-US', { month: 'long' }) +' vs '+ prvDateMonth.toLocaleString('en-US', { month: 'long' }));