admin管理员组文章数量:1318572
I would like to see if a date object is over one year old! I don't know how to even pare them due to the leap years etc..
var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();
if(???) {
console.log("it has been over one year!");
} else {
console.log("it has not gone one year yet!");
}
I would like to see if a date object is over one year old! I don't know how to even pare them due to the leap years etc..
var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();
if(???) {
console.log("it has been over one year!");
} else {
console.log("it has not gone one year yet!");
}
Share
Improve this question
asked Oct 2, 2015 at 19:48
basickarlbasickarl
40.6k69 gold badges238 silver badges355 bronze badges
2
- Possible duplicate of Difference between dates in JavaScript – Paul Roub Commented Oct 2, 2015 at 20:00
- Note this answer which specifically shows how to alert when the difference is > 365 days. – Paul Roub Commented Oct 2, 2015 at 20:00
3 Answers
Reset to default 6You could make the check like this
(todayDate - oldDate) / (1000 * 3600 * 24 * 365) > 1
You can see and try it here:
https://jsfiddle/rnyxzLc2/
This code should handle leap years correctly.
Essentially:
If the difference between the dates' getFullYear()
is more than one,
or the difference equals one and todayDate
is greater than oldDate
after setting their years to be the same,
then there's more than a one-year difference.
var oldDate = new Date("Oct 2, 2014 01:15:23"),
todayDate = new Date(),
y1= oldDate.getFullYear(),
y2= todayDate.getFullYear(),
d1= new Date(oldDate).setFullYear(2000),
d2= new Date(todayDate).setFullYear(2000);
console.log(y2 - y1 > 1 || (y2 - y1 == 1 && d2 > d1));
use getFullYear()
:
fiddle: https://jsfiddle/husgce6w/
var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();
var thisYear = todayDate.getFullYear();
var thatYear = oldDate.getFullYear();
console.log(todayDate);
console.log(thatYear);
if(thisYear - thatYear > 1) {
console.log("it has been over one year!");
} else {
console.log("it has not gone one year yet!");
}
本文标签: javascriptCheck if date object is over one year oldStack Overflow
版权声明:本文标题:javascript - Check if date object is over one year old - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742048208a2417918.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论