Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding/Subtracting days from a date doesn't change the year/month correctly

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

like image 658
Amir Avatar asked Dec 01 '10 00:12

Amir


2 Answers

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

jsFiddle example

like image 135
Jacob Relkin Avatar answered Sep 20 '22 03:09

Jacob Relkin


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.

like image 35
Gordon Gustafson Avatar answered Sep 22 '22 03:09

Gordon Gustafson