Categories
JavaScript Answers

How to Calculate Age from the Date of Birth Using jQuery?

Spread the love

To calculate age from date of birth using jQuery, we can use native JavaScript date methods.

For instance, we can write the following HTML:

<div>

</div>

Then we write:

const dt = new Date();
dt.setFullYear(dt.getFullYear() - 18);

$('div').text((dt.getTime() - new Date(1990, 5, 6).getTime() < 0) ? "Under 18" : "Over 18");

to create the dt date object with that we set to 18 years before today.

Then we call text with dt.getTime() — new Date(1990, 5, 6).getTime() < 0) ? “Under 18” : “Over 18” to check if the date is after the day that’s 18 years before today with:

dt.getTime() — new Date(1990, 5, 6).getTime() < 0

If it is, then we set the div’s text to 'Under 18' .

Otherwise, we set it to 'Over 18' .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *