Luxon.js get difference between now and input date in years

J. Doe picture J. Doe · Nov 18, 2019 · Viewed 8.5k times · Source

I'm using luxon.js and want to check, is the user's age is over than 21 years. Code, that i'm using for it

const isTooYoung = date =>
  DateTime.fromFormat(date, 'dd.MM.yyyy')
    .diffNow()
    .as('years') < -21;

But for todays' s day (18.11.2019) both calls:

console.log(isTooYoung('15.11.1998')); // true => incorrect
console.log(isTooYoung('20.11.1998')); // true => correct, this user is not 21 year old yet

fiddle: http://jsfiddle.net/zh4ub62j/1/

So, what is correct way to solve problem to check, is the user's age is over than x years?

Answer

snickersnack picture snickersnack · Nov 27, 2019

Converting between Duration units is lossy, because years aren't all the same length, and Luxon has "lost" the knowledge that the the duration came from that particular span of time. There's a section about this in the docs: https://moment.github.io/luxon/docs/manual/math.html#losing-information

Fortunately, the workaround is easy: just do the diff in years. Then Luxon will know to do the math in terms of real calendar years:

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

Fiddle: http://jsfiddle.net/j8n7g4d6/