patternjavascriptModerate
Is date 18+ years old?
Viewed 0 times
olddateyears
Problem
Considering that:
It should return:
Despite I don't want to lose maintainability and readability, I feel it could possibly have a lesser number of conditional statements.
Is there any improvement you suggest?
Also, if you spot any cases that the function fails it's very welcome.
- the passed parameters are all numbers
- the passed date is a valid date
It should return:
trueif the date is 18 or more years old
falseotherwise
function isDate18orMoreYearsOld(day, month, year) {
var maxBirthDate = new Date();
maxBirthDate = new Date(maxBirthDate.setYear(maxBirthDate.getYear() - 18));
var maxYear = maxBirthDate.getYear();
var maxMonthOnMaxYear = maxBirthDate.getMonth() + 1;
var maxDayOnMaxMonthOnMaxYear = maxBirthDate.getDate();
if (year > maxYear) {
return true;
}
if (year == maxYear) {
if (month > maxMonthOnMaxYear) {
return true;
}
if (month == maxMonthOnMaxYear) {
if (day >= maxDayOnMaxMonthOnMaxYear) {
return true;
}
}
}
return false;
}Despite I don't want to lose maintainability and readability, I feel it could possibly have a lesser number of conditional statements.
Is there any improvement you suggest?
Also, if you spot any cases that the function fails it's very welcome.
Solution
What about this:
The
function isDate18orMoreYearsOld(day, month, year) {
return new Date(year+18, month-1, day) <= new Date();
}The
month - 1 is required because JS months start at 0.Code Snippets
function isDate18orMoreYearsOld(day, month, year) {
return new Date(year+18, month-1, day) <= new Date();
}Context
StackExchange Code Review Q#118272, answer score: 16
Revisions (0)
No revisions yet.