Javascript 从日期中添加/减去天数不会正确更改年/月
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4320019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding/Subtracting days from a date doesn't change the year/month correctly
提问by Amir
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
?
如果我有一个日期2011-01-02
并且我7
从那个日期减去天数,它应该给我2010-12-26
,但它给了我2011-01-26
?
See the JS below to verify with link:
请参阅下面的 JS 以通过链接进行验证:
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);
回答by Jacob Relkin
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
jsFiddle 示例
回答by Gordon Gustafson
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:
getDate()
并且setDate()
两者都只指日期的月份部分。为了减去7
你想要这样做的天数:
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.
这将一个月中的某一天设置为该月的某一天减去七。如果您最终使用负数,则返回到上个月。
回答by simshaun
.getDate() only returns the day of the month, and .setDate() only sets the DAY of the month, not the date.
.getDate() 只返回月份中的第几天,而 .setDate() 只设置月份中的第几天,而不是日期。
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);
回答by Gaurav
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; } }
我写了一个实用程序 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);