moment.js,比较日与年的差异
moment.js, comparing diff with days vs year
我有这两种方法来确定某个时间差是否大于或等于 1 年。我有日期和年份的比较,我想知道它们是否有问题,以及使用哪个。
// this date is an example date, it could be any from last 20 years
const userDateOld = '2001-10-20T00:00:00.000+00:00';
const dateOld = moment.utc(userDateOld);
const ruleDate = moment.utc().subtract({year: 1}).endOf('year');
const antiquityYears = ruleDate.diff(dateOld, 'years');
if (antiquityYears >= 1) { // at least 1 year to 31 december last year
console.log('Yes, it has at least 1 year to 31 dec last year');
}
const contractedDays = ruleDate.diff(dateOld, 'days');
if (contractedDays >= 365) { // should be the same but comparing year
console.log('Yes, it ALSO has at least 1 year to 31 dec last year');
}
我有这个 fiddle 来测试代码:https://jsfiddle.net/pmiranda/9bpkLuhz/
年份是更好的解决方案,因为它考虑了闰年,365
天的常数不是。
找到相关参考
您可以在下面看到这样的示例:
const coreDate = moment.utc.now;
const dateOld = moment.utc(coreDate);
const ruleDate = moment.utc(coreDate).subtract({year: 5});
const antiquityYears = dateOld.diff(ruleDate, 'years');
const contractedDays = dateOld.diff(ruleDate, 'days');
console.log("years passed :"+antiquityYears);
console.log("days passed :"+contractedDays);
console.log("years passed /5 :"+(antiquityYears/5));
console.log("days passed /365 :"+(contractedDays/365));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
我有这两种方法来确定某个时间差是否大于或等于 1 年。我有日期和年份的比较,我想知道它们是否有问题,以及使用哪个。
// this date is an example date, it could be any from last 20 years
const userDateOld = '2001-10-20T00:00:00.000+00:00';
const dateOld = moment.utc(userDateOld);
const ruleDate = moment.utc().subtract({year: 1}).endOf('year');
const antiquityYears = ruleDate.diff(dateOld, 'years');
if (antiquityYears >= 1) { // at least 1 year to 31 december last year
console.log('Yes, it has at least 1 year to 31 dec last year');
}
const contractedDays = ruleDate.diff(dateOld, 'days');
if (contractedDays >= 365) { // should be the same but comparing year
console.log('Yes, it ALSO has at least 1 year to 31 dec last year');
}
我有这个 fiddle 来测试代码:https://jsfiddle.net/pmiranda/9bpkLuhz/
年份是更好的解决方案,因为它考虑了闰年,365
天的常数不是。
您可以在下面看到这样的示例:
const coreDate = moment.utc.now;
const dateOld = moment.utc(coreDate);
const ruleDate = moment.utc(coreDate).subtract({year: 5});
const antiquityYears = dateOld.diff(ruleDate, 'years');
const contractedDays = dateOld.diff(ruleDate, 'days');
console.log("years passed :"+antiquityYears);
console.log("days passed :"+contractedDays);
console.log("years passed /5 :"+(antiquityYears/5));
console.log("days passed /365 :"+(contractedDays/365));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>