Skip to main content
6 of 6
edited tags
200_success
  • 144.2k
  • 22
  • 188
  • 473

Is date 18+ years old?

Considering that:

  • the passed parameters are all numbers
  • the passed date is a valid date

It should return:

  • true if the date is 18 or more years old
  • false otherwise

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.

falsarella
  • 218
  • 1
  • 3
  • 12