68

Please anyone share the code to find the previous month's first date from current date in JavaScript. For example, if the current date is 25th Jan 2009, I should get 1st Dec 2008 as result.

  • Possible duplicate [Find first day of previous month in javascript](http://stackoverflow.com/questions/605113/find-first-day-of-previous-month-in-javascript) –  Nov 04 '12 at 13:56
  • Check this : http://stackoverflow.com/questions/605113/find-first-day-of-previous-month-in-javascript – Learning Mar 03 '09 at 08:55

12 Answers12

99

Straightforward enough, with the date methods:

  var x = new Date();
  x.setDate(1);
  x.setMonth(x.getMonth()-1);
smfoote
  • 5,449
  • 5
  • 32
  • 38
annakata
  • 74,572
  • 17
  • 113
  • 180
97

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
Reza Ghorbani
  • 2,396
  • 2
  • 28
  • 33
  • 6
    This works in all cases I have tested: regular days, 31st of a month, 28th of leap year February, January 1st (rolling back to December of the previous year). It just works and should be the accepted answer. Crazy that this question was posed in 2009. – Devin Fields Oct 31 '18 at 19:30
  • 5
    Most underappreciated answer I've seen on SO. – Annosz Nov 22 '19 at 14:52
  • I know slightly off topic but why doesnt this work when setting the date like so: new Date(2020, 1, 1) but works with new Date()? – Mafster Dec 10 '20 at 01:51
  • 1
    @Mafster Its because month starts at 0. You are actually showing February first. – Reza Ghorbani Dec 12 '20 at 20:50
  • 1
    Just to clarify to anyone who doesn't understand the approach, this works because `x.setDate(0)` is setting the date to last months last day and since the date is now referencing last month, when you do `x.setDate(1)` it gets you the first day of that month. Pretty nice solution. – ricks Oct 12 '21 at 17:10
  • Same principle works for getting a date in the next month using `32` (or more) instead of `0`: `x.setDate(32);` (results in a date near the start of next month) – Redzarf Jan 11 '22 at 16:03
8

Important Note: Some of the answers using setMonth() here are wrong:

One liners for use in 2019 (using ES6 syntax; supported by all major browsers and Node):

    const date = new Date().toISOString(); // "2019-09-18T13:49:12.775Z"
    const [yyyy, mm, dd, h, i, s] = date.split(/T|:|-/);


    // previous month's last day
    const prev = new Date(new Date().setDate(0)).toISOString();
    const [pyyyy, pmm] = prev.split(/T|:|-/);

Note that Array destructuring allows you to skip parts:

    const date = new Date().toISOString();
    const [, , dd, , i] = date.split(/T|:|-/);

Explanation: The code above gets the ISO date 2019-09-18T13:49:12.775Z and splits it on : or - or T which returns an array [2019, 09, 18, 13, 49, 12] which then gets destructured.

Using setMonth() is wrong:

date = new Date("Dec 31, 2019")
date.setMonth(date.getMonth() - 1);
date; // Dec 1, 2019!
aleemb
  • 31,265
  • 19
  • 98
  • 114
6

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>
googamanga
  • 172
  • 1
  • 8
4

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' }));
4

Check this link:

http://blog.dansnetwork.com/2008/09/18/javascript-date-object-adding-and-subtracting-months/

EDIT: I have drummed up an example:

Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
d.setDate(1);
return d;
}

$(document).ready(function() {
    var d = new Date();
    alert(d.SubtractMonth(1));
});
Penguin
  • 169
  • 3
  • 14
REA_ANDREW
  • 10,666
  • 8
  • 48
  • 71
  • Hi Andrew, the solution you told returns exact 30 days back from current date. I need first date of the previous month irrespective of any date in current month. –  Mar 03 '09 at 08:50
  • This solution dose not work. Date.setMonth() dose not accept negative values except -1 which will result in the last month of the previous year http://www.w3schools.com/jsref/jsref_setmonth.asp – idragosalex Dec 16 '13 at 08:18
  • This answer is buggy, it'll fail for "Dec 31, 2018" for example – aleemb Sep 19 '19 at 11:29
2

To get 00:00:00 am of previous month use this:

let d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);
d.setHours(0,0,0,0);
const lastMonthStart = new Date(d);

Hope this helps!!

Harshit Agarwal
  • 2,308
  • 2
  • 15
  • 23
2
//  Previous Month Detail
let prevStartDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1, 1);
console.log(prevStartDate);
let preEndDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1 + 1, 0);
console.log(preEndDate);
//Current Month Detail
let cStartDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1);
console.log(cStartDate);
let cEndDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0);
console.log(cEndDate);
//Next Month Detail
let nStartDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1, 1);
console.log(nStartDate);
let nendDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1 + 1, 0);
console.log(nendDate);
1

//just try this will work fine

let date = new Date();
let month = new Date().getMonth();
let prevMonth = date.setMonth(month - 1)
let formatPrevMonth = new Date(date.setMonth(month - 1));

console.log(formatPrevMonth)
ahmed mersal
  • 167
  • 2
  • 3
0

Here, first we assign getMonth() to a variable and incremented it by 1:

var currentMonth = date.getMonth()+1;
var current_date = date.getFullYear()+"/"+currentMonth+"/"+date.getDate();
document.getElementById("p3").innerHTML = "Today,s date:"+current_date;
Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
  • I see you assume some HTML to be present. But you are sharing only your JS. Can you edit your answer and append your HTML to it as well, preferably in a functional snippet? – Lajos Arpad Sep 25 '22 at 20:16
0

This can easily be achieved by creating a Date object based on the input date object and changing the date to 1, decrementing the year if it was January and decrementing the month (modulo 12). An important addition to it is to subtract the offset as well.

function getFirstOfPreviousMonth(date) {
    let result = new Date(date.getFullYear() - (date.getMonth() ? 0 : 1), (date.getMonth() + 11) % 12, 1);
    return new Date(result.getTime() - result.getTimezoneOffset() * 60000);
}

console.log(getFirstOfPreviousMonth(new Date()));
console.log(getFirstOfPreviousMonth(new Date(2009, 0, 25)));
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

Reactjs
This code below works for me

const onDateButtonClick = (event) => {
if (event) {

  // once on click get the name and use switch case to get date
  var eDate = new Date()
  var sDate;
  var dName = event.target.id;
  switch (dName) {
    case '1w':
      sDate = new Date(eDate.getFullYear(), eDate.getMonth(), eDate.getDate() - 7);
      break;
    case '2w':
      sDate = new Date(eDate.getFullYear(), eDate.getMonth(), eDate.getDate() - 14);
      break;
    case '1m':
      sDate = new Date(eDate.getFullYear(), eDate.getMonth() - 1, eDate.getDate());
      break;
    case '2m':
      sDate = new Date(eDate.getFullYear(), eDate.getMonth() - 2, eDate.getDate());
      break;
  }
}
tyler_flx
  • 11
  • 1