从日期添加/减去日期不会正确地更改年/月 [英] Adding/Subtracting days from a date doesn't change the year/month correctly

查看:129
本文介绍了从日期添加/减去日期不会正确地更改年/月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的日期是 2011-01-02 ,我从那个日期减去 7 天应该给我 2010-12-26 ,而是给我 2011-01-26

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

jsFiddle例如

这篇关于从日期添加/减去日期不会正确地更改年/月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆