本文介绍了JS:如何检查给定的日期是否在今天之后的2年之内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a date time in milliseconds, how do I check if its within 2 years of today in JavaScript ? So far, I have the following:

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

这是正确的吗?如何解释leap年之类的事情?

Is this correct ? How do account for things like leap years ?

推荐答案

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

Just at 2 years to today and see if it's greater than the supplied date or time value, e.g.

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

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

这篇关于JS:如何检查给定的日期是否在今天之后的2年之内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 07:14