Reputation: 2277
If I have a date that is 2011-01-02
and I subtract 7
days from that date it should give me 2010-12-26
, but instead it gives me 2011-01-26
?
See the JS below to verify with link:
var date = new Date('2011','01','02');
alert('the original date is '+date);
var newdate = new Date(date);
newdate = newdate.setDate(newdate.getDate() - 7);
var nd = new Date(newdate);
alert('the new date is '+nd);
Upvotes: 8
Views: 28168
Reputation: 859
i have written a utility program Date.prototype.subDuration = subDuration; function subDuration(a,b) { if ((typeof a === 'string')&&(typeof b === 'number')){ if ((a ==="Add") || (a ==="Sub")){ subdur.call(this,a,b) }else{ return false; } }
function subdur(action,days){
switch (action){
case 'Add':
addDays.call(this,days);
break;
case 'Sub':
rmvDays.call(this,days)
break;
default:
return false;
}
function addDays(days){
this.setDate(this.getDate()+days)
};
function rmvDays(days){
this.setDate(this.getDate()-days);
};
}
}
var d = new Date('2011','00','02');
alert(d);
d.subDuration('Add',2);
alert(d);
d.subDuration('Sub',3);
alert(d);
Upvotes: 0
Reputation: 41249
getDate()
and setDate()
both refer to only the day of the month part of the date. In order to subtract 7
days you want to do this:
myDate.setDate( myDate.getDate() - 7 );
This sets the day of the month to the day of the month minus seven. If you end up using a negative number it goes back to the previous month.
Upvotes: 4
Reputation: 21466
.getDate() only returns the day of the month, and .setDate() only sets the DAY of the month, not the date.
Try doing
var date = new Date('2011','01','02');
alert('the original date is '+date);
var newdate = new Date(date.getTime() - 604800000);
alert('the new date is '+newdate);
Upvotes: 2
Reputation: 163288
I think you meant to do this: (working perfectly)
var date = new Date('2011','01','02');
alert('the original date is '+date);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() - 7);
var nd = new Date(newdate);
alert('the new date is '+nd);
Upvotes: 20