简体   繁体   English

JS:如何检查给定的日期是否从今天算起两年内?

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

If I have a date time in milliseconds, how do I check if its within 2 years of today in JavaScript ? 如果我有一个以毫秒为单位的日期时间,如何在JavaScript中检查它是否在今天的2年之内? 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 ? 如何解释leap年这样的事情?

Just at 2 years to today and see if it's greater than the supplied date or time value, eg 距今天仅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') } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM