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);
http://jsbin.com/upeyu/6
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With