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

1

14

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?

Cheyennecheyne answered 18/11, 2019 at 10:59 Comment(0)
H
24

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/

Hippolytus answered 27/11, 2019 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.