我正在使用luxon.js并要检查,因为用户的年龄超过21岁。 我正在使用的代码
const isTooYoung = date =>
DateTime.fromFormat(date, 'dd.MM.yyyy')
.diffNow()
.as('years') < -21;
但在今天(2019年11月18日)都打电话:
console.log(isTooYoung('15.11.1998')); // true => incorrect
console.log(isTooYoung('20.11.1998')); // true => correct, this user is not 21 year old yet
提琴:http://jsfiddle.net/zh4ub62j/1/
那么,解决问题的正确方法是什么?用户的年龄超过x年吗?
答案 0 :(得分:0)
在工期单位之间进行转换是有损失的,因为年长不尽相同,而且卢克森“迷失了”知道工期来自那个特定时间跨度的知识。文档中有关于此内容的部分:https://moment.github.io/luxon/docs/manual/math.html#losing-information
幸运的是,解决方法很简单:只需数年即可完成比较。然后,卢森堡会知道按照实际日历年进行数学运算:
// now is 27.11.2019
const isTooYoung = date =>
luxon.DateTime.fromFormat(date, 'dd.MM.yyyy')
.diffNow('years')
.years < -21;
console.log(isTooYoung('15.11.1998'))
console.log(isTooYoung('30.11.1998'))