开发者

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 Da开发者_Go百科te(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);

jsFiddle example


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.


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜