JavaScript

JavaScript Made Easy! Automatically Calculate and Display Age from Date of Birth

In this article, we’ll explain in detail how to use JavaScript to calculate a person’s current age from their date of birth and display it on a web page. This technique can enhance the user interface depending on how it’s used.

What is the CSS for Calculating Age from Date of Birth?

First, let’s style the element (.birthage) where the age will be displayed. Here is some CSS to balance readability and visual appeal.

<style>
body {
  margin: 20px 10px;
  padding: 0;
  font-size: 18px;
  text-align: center;
}
h1{
  text-align: center;
  font-size: 22px;
  line-height: 2em;
  padding-bottom: 20px;
}
.birthage{
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  color: red;
  padding: 15px 0;
}
</style>

This style makes the age stand out and is designed to fit easily into any part of the web page.

HTML and JavaScript to Calculate Age from Date of Birth

Now, the core part. Here’s the JavaScript code that calculates a person’s age from their date of birth and displays it on the page. This script uses the Date object to calculate the number of years from the birth date to today.

We’ve prepared a function called getage(year, month, day) that returns the age. It uses Date() to get this year’s birthday and calculates the age from it. The result from getage() is displayed using document.write().

<h1>Display Current Age from Date of Birth Using JavaScript</h1>

<div align="center">A person born on January 15, 1992 is currently:</div>

<script type="text/javascript">
function getage(y,m,d){
    var today = new Date(); // Get today's date
    var thisYearsBirthday = new Date(today.getFullYear(), m-1, d);  // Get this year’s birthday
    var age = today.getFullYear() - y;  // Calculate age
    // Subtract 1 if birthday hasn't occurred yet this year
    if(today < thisYearsBirthday){
        age--;
    }
    return age;
}

y=1992;
m=1;
d=15;
document.write('<div class="birthage">'+getage(y,m,d)+' years old</div>');
</script>

This code is simple yet clearly demonstrates the logic of age calculation.

Demo Page: Display Current Age from Date of Birth Using JavaScript

You can view the live demo page from the link below. Try entering different birthdates and see how the age is calculated instantly.

Demo Page: Display Current Age from Date of Birth Using JavaScript

Conclusion

In this article, we introduced how to use JavaScript to calculate age from a date of birth and display it on a webpage. Drawing on my experience as an engineer, I’ve made the explanation easy to understand for readers. This technique will surely expand your web development capabilities. Give it a try!

 
*Please use this code at your own risk if you plan to reuse it.
Do not reuse the Google Analytics tag included in the demo page’s head tag.