JS : How to check if given date is within 2 years from today?

不问归期 提交于 2019-12-13 03:43:44

问题


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

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


回答1:


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


来源:https://stackoverflow.com/questions/48897780/js-how-to-check-if-given-date-is-within-2-years-from-today

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!