Calculate age in years using JavaScript

In this short article, we will show you how to calculate age in years using JavaScript. We’ll learn how to calculate the user’s age from their date of birth and return in years.

Here we’ll discuss a few different ways to calculate age in years using JavaScript.

Different ways to calculate age

  1. Calculate age using JavaScript
  2. Calculate age using Moment JS

1. Calculate age using JavaScript

We will create a simple function to calculate age in years by passing the date of birth. Check out the following function to calculate age.

We have used two parameters in the above function. The date of birth will pass in the first parameter and the second parameter is optional where we can pass the date to get a difference. By default, we have considered the second parameter as the current date.

2. Calculate age using Moment JS

If you have already installed Moment.js in your project then you can use the following code to get age in years format.

If you are facing any issue to integrate the moment.js then simply add the following script in the head section of the page to use the moment function.

Check out the article: Time from now using Moment JS

That’s it for today.
Thank you for reading. Happy Coding..!!

You may also like...

Leave a Reply

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