You can use JavaScript’s Date object and some arithmetic to check if a person’s age is not less than 18 years. Here’s an example:

function isAdult(birthDate) {
  var ageDifMs = Date.now() - birthDate.getTime();
  var ageDate = new Date(ageDifMs); // miliseconds from epoch
  return Math.abs(ageDate.getUTCFullYear() - 1970) >= 18;
}
console.log(isAdult(new Date(2003, 2, 1)));  // Output: false
console.log(isAdult(new Date(2003, 2, 1,1,1,1,1)));  // Output: false
console.log(isAdult(new Date(2002, 2, 1)));  // Output: true
console.log(isAdult(new Date(2002, 2, 1,1,1,1,1)));  // Output: true

In this example, the isAdult() function takes a single argument, the birth date of the person in question. The function calculates the difference between the current date and the birth date in milliseconds using the Date.now() function and the getTime() method of the Date object. It then creates a new Date object using this difference, and calculates the person’s age by subtracting 1970 from the getUTCFullYear() method of the new date object.

Finally, it returns true if the age is greater than or equal to 18 and false if not.

Note: The above code snippet assumes that the birthdate passed is a javascript Date object.

Also Read:

Categorized in: