I am using moment.js. I want to restrict the user son that he can only select a date which is from current date to 50 years before. In short, i just want that user's date of birth cannot be more than 50 years. So, from the current date, only ranges before the 50 years should only be there. How can i do so? please guide me.
CodePudding user response:
So you have to calculate 50 years back date first https://momentjs.com/docs/#/manipulating/subtract/
fiftyYearsBackDate = moment().subtract(50, "years")
Get user Selected date
userDate = new Date()
Create moment object from that and do query https://momentjs.com/docs/#/query/is-after/
moment(userDate).isAfter(fiftyYearsBackDate)
this will return boolean
that you can use to show the error message.
CodePudding user response:
You want to calculate the difference
in years between now and the birthdate, and check if it's bigger than 50.
const birthDate = '1970-01-01'
const yearsDiff = moment().diff(birthDate, 'years');
If you want to get the difference of years in decimal:
const yearsDiff = moment().diff(birthDate, 'years', true);
The yearsDiff
will contain the difference, so you can do an if
check on it to see if it's bigger than 50.
Official docs for this: https://momentjs.com/docs/#/displaying/difference/
CodePudding user response:
By using moment js you can easily get past and future dates like this -
const past = moment().subtract(50, 'years'); // To past
const future = moment().add(50, 'years'); // Back to future
Finally
const today = moment();
moment(today).isAfter(past, 'year'); // return: true || false
The reference site URL is - https://everyday.codes/javascript/how-to-format-date-in-javascript-with-moment-js/