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:
- Difference Between encodeURIComponent() And encodeURI()
- Convert Comma Separated String Into An Array In JavaScript
- How To Check If A String Is Empty In JavaScript
- How To Sort An Array Of Numbers In JavaScript
- How To Return Multiple Values From A Function In JavaScript
- How To Get The Current URL With JavaScript
- How To Include A JavaScript File In Another JavaScript File
- How To Detect Screen Resolution With JavaScript
- How To parse JSON Into JavaScript
- How To Add Elements To An Array In JavaScript
- How To Generate A Timestamp In JavaScript
- How To Convert A JavaScript Object To JSON String
- How To Add An Element To The Beginning Of An Array
- How To Get The Value From The Input Field In JavaScript
- Adjust The iFrame Height To Fit With Content In JavaScript
- Call Two Functions From The Same onClick Event In JavaScript
- How To Detect When A Window Is Resized Using JavaScript
- How To Reset A Form With JavaScript
- How To Pass JavaScript Variables To PHP
- Difference Between PHP And JavaScript
- Armstrong Number In JavaScript
- How To Determine If A Number Is Odd Or Even In JavaScript
- How To Check If A Number Is A Palindrome In JavaScript
- How To Convert Strings To Uppercase In JavaScript
- How To Convert A String To Lowercase In JavaScript
- Code To Check If Age Is Not Less Than 18 Years In JavaScript
- How To Reverse A Number In JavaScript
- How To Check If A Number Is Prime Using JavaScript
- How To Find Factorial Of A Number In JavaScript
- Sum Of Two Numbers In JavaScript
- How To Display The Current Date And Time In JavaScript