3

How can I get previous month date in javascript. Suppose you have today's date like:

var abc = new date(); 

It will return today's date for example 03-11-2015. Now I want to get 03-10-2015. This is 30 days less than todays date. How can I do this?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Vicky
  • 257
  • 2
  • 5
  • 11

2 Answers2

12
var d = new Date();
d.setMonth(d.getMonth() - 1);

Check out momentjs, great little library for manipulating and formatting dates.

  • If you use setMonth(getMonth() - 1) on March 1, you'll get February 1 as an answer. If you're going for 30 days, try setDate(getDate() - 30). As of 2021, Momentjs' site advice us to look for alternatives to it https://momentjs.com/docs/#/-project-status/. – isacvale May 31 '21 at 14:28
10

Complementing Robert Shenton's answer:

var d = new Date();
var newMonth = d.getMonth() - 1;
if(newMonth < 0){
    newMonth += 12;
    d.setYear(d.getFullYear() - 1); // use getFullYear instead of getYear !
}
d.setMonth(newMonth);
Lyokolux
  • 1,227
  • 2
  • 10
  • 34
Bustikiller
  • 2,423
  • 2
  • 16
  • 34
  • Thank you if I want to format the date to dd/MM/yyyy then I have to write .format() or .tostring()? – Vicky Nov 03 '15 at 04:05
  • Maybe you are looking for .toLocaleDateString() which will use a different format depending on the conventions of the visitor's language. http://www.w3schools.com/jsref/jsref_tolocaledatestring.asp – Bustikiller Nov 03 '15 at 05:07
  • Yes I got it thanks. I have used format() for this. It works fine. – Vicky Nov 03 '15 at 17:40
  • And yes moment.js is a very good javascript library. – Vicky Nov 03 '15 at 17:42
  • Would this ever hit December? 0-1 = -1 then -1+12 = 11, never hitting december. You would actually need to add 13, right? – Juan Pablo Ugas Jan 13 '17 at 21:04
  • ahhh man, long week. Of course it would since we're counting 0 as 1, smh. My bad, and good work, this helped me out! – Juan Pablo Ugas Jan 13 '17 at 21:09
  • you should use d.getFullYear() -1 instead of d.getYear() -1 – Brian McCall Jan 11 '19 at 05:47
  • 2
    Checking for negative month is not necessary, as `var d = new Date(); d.setMonth(-1)` works as expected - for January 10, 2020 it results in December 10, 2019. So Robert Shenton's answer is sufficient. – mrts Mar 03 '20 at 13:46