tags:

views:

1358

answers:

3

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.


Duplicate of: http://stackoverflow.com/questions/605113/find-first-day-of-previous-month-in-javascript

+1  A: 

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

Andrew

REA_ANDREW
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.
thanks dude !!!!i got it
+2  A: 

Straightforward enough, with the date methods:

  var x = new Date();

  with(x)
  {
    setMonth(getMonth()-1);
    setDate(1);
  }
annakata
except it misses when the year changes?
Learning
No it does that will auto adjust the date
REA_ANDREW
This is why you do this with the native date methods rather than messing around with your own calendar arithmatic. God I love JS :)
annakata
i.e. using his example substitute 1 for 5 say and the year will be 2008
REA_ANDREW
A: 

Check this :

http://stackoverflow.com/questions/605113/find-first-day-of-previous-month-in-javascript

Learning
good spot - voting for close
annakata