admin管理员组文章数量:1243219
I'm trying to perform date manipulations using JavaScript on a single line, and I'm having problems with the year (not the month or day). I got the idea from this link. Am I missing something?
The code is as follows:
var newyear = new Date((new Date()).getYear(), (new Date()).getMonth(), (new Date()).getDate()+5).getFullYear();
document.write(newyear);
This gives me "110".
I'm not sure why? Thanks!
I'm trying to perform date manipulations using JavaScript on a single line, and I'm having problems with the year (not the month or day). I got the idea from this link. Am I missing something?
The code is as follows:
var newyear = new Date((new Date()).getYear(), (new Date()).getMonth(), (new Date()).getDate()+5).getFullYear();
document.write(newyear);
This gives me "110".
I'm not sure why? Thanks!
Share Improve this question asked Feb 25, 2010 at 21:09 RioRio 14.9k22 gold badges71 silver badges109 bronze badges 4-
Why is
newyear
only 5 days after now? – kennytm Commented Feb 25, 2010 at 21:13 - Oddly, works in IE 7, yielding "2010". Haven't bothered to test in other browsers. – jball Commented Feb 25, 2010 at 21:15
- @jball: Yeah. IE is always the one that stands out. – kennytm Commented Feb 25, 2010 at 21:17
-
A little testing shows that IE treats both
getYear()
andgetFullYear()
identically. More reasons not to use deprecated functions. – jball Commented Feb 25, 2010 at 21:22
3 Answers
Reset to default 15(new Date()).getYear()
You should use getFullYear()
here. getYear()
in JS means (year − 1900).
var newyear = new Date((new Date()).getFullYear(), (new Date()).getMonth(), (new Date()).getDate()+5).getFullYear();
Y2K bug aside, this is a simpler expression:
var newyear = new Date(new Date().setDate(new Date().getDate()+5)).getFullYear()
Date objects are relatively expensive and you can do this with a single Date object and less code if you don't assume it has to be a single expression.
var d = new Date(); d.setDate(d.getDate()+5); var newyear = d.getFullYear()
本文标签: datetimeAdding dates in JavaScript in one lineStack Overflow
版权声明:本文标题:datetime - Adding dates in JavaScript in one line - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740130913a2229730.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论