JS:如何检查给定日期是否在今天之后的2年内?

时间:2018-02-21 03:34:18

标签: javascript date date-difference

如果我有一个以毫秒为单位的日期时间,我如何在今天的2年内检查它是否在JavaScript中?到目前为止,我有以下内容:

var yearInMs = ( 1000 * 60 * 60 * 24 * 7 * 52 );
var givenTime = 1519183763504;
var diff =  givenTime - ( new Date().getTime());
diff = diff / yearInMs;
if( diff > 2 )
   alert('more than 2 years');

这是对的吗?如何解释像闰年这样的事情?

1 个答案:

答案 0 :(得分:0)

距离今天仅2年,看看它是否大于提供的日期或时间值,例如



var d = new Date();
d.setFullYear(d.getFullYear() + 2);

if (d > 1519183763504) {
  console.log('within  2 years')
} else {
  console.log('Not within  2 years')
}