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
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.
1 2 3 4 5 6 7 | function calculateAge(dob, dt) { dt = dt || new Date(); var diff = dt.getTime() - new Date(dob).getTime(); return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25)); } calculateAge("2000-08-27"); // Output: 20 |
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.
1 | moment().diff('2000-08-27', 'years'); // Output: 20 |
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.
1 | <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script> |
Check out the article: Time from now using Moment JS
That’s it for today.
Thank you for reading. Happy Coding..!!