Amir
Amir

Reputation: 2277

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

Upvotes: 8

Views: 28168

Answers (5)

Gaurav
Gaurav

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

Gordon Gustafson
Gordon Gustafson

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

simshaun
simshaun

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

Jacob Relkin
Jacob Relkin

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

jsFiddle example

Upvotes: 20

Gareth
Gareth

Reputation: 138160

This is because the setDate method is only supposed to set the day of the month

Upvotes: 0

Related Questions