Age Calculator with HTML, CSS & JavaScript
30 DAYS 30 PROJECT CHALLENGE
Day #18
Project Overview
The Age Calculator is a beginner-friendly project built using HTML, CSS, and JavaScript. It allows users to enter their date of birth and calculate their current age in years, months, and days.
This project uses JavaScript’s Date object to work with dates and compare the user’s date of birth with the current date. It calculates the difference between the two dates and adjusts the values when the current day or month is earlier than the birth day or month.
This project helps beginners understand how JavaScript handles dates and calculations. It introduces concepts such as user input, date manipulation, conditional statements, functions, validation, and dynamic DOM updates.
Key Features
- Date of Birth Input: Users can select their date of birth using a date input field. This provides an easy way to enter the information required for the age calculation.
- Age Calculation: The application calculates the user’s age based on the selected date of birth and the current date. The result is calculated automatically using JavaScript date values.
- Years, Months, and Days: The calculated result displays the user’s age in years, months, and days. This provides a more detailed result than showing only the total number of years.
- Input Validation: JavaScript checks whether the user has selected a valid date before performing the calculation. This helps prevent the application from displaying incorrect results.
- Future Date Validation: The application can check whether the selected date is in the future. If an invalid future date is selected, an appropriate message can be displayed.
- Dynamic Result Display: JavaScript updates the result area immediately after calculating the age. Users can see their age without refreshing the webpage.
- Date Manipulation: The project uses JavaScript date methods to compare the birth date with the current date. Conditional logic helps adjust the months and days when required.
- Simple and Clean Interface: The application uses a straightforward layout containing a date input, calculation button, and result area. This makes the project easy for beginners to understand and use.
- Responsive Design: The Age Calculator can adjust to different screen sizes and remain comfortable to use on desktops, tablets, and mobile devices.
- Easy to Extend: Developers can add additional features such as the next birthday countdown, total days lived, zodiac information, or age calculation for different dates.
What You'll Learn
- Understand how JavaScript works with dates.
- Learn how to use the JavaScript
Dateobject. - Practice reading values from a date input.
- Understand how to compare two dates.
- Learn how to get the current date using JavaScript.
- Practice calculating differences between dates.
- Understand how conditional statements adjust date values.
- Learn how input validation works.
- Practice creating functions for calculations.
- Understand how JavaScript updates HTML dynamically.
- Learn how to display calculated results on a webpage.
HTML Code
HTML creates the structure of the Age Calculator. First, the style.css file is linked inside the <head> section so CSS can control the appearance of the application. The main content is placed inside the .calculator container, which contains the project heading, date label, date input, Calculate Age button, and result area.
This <input> element with the ID dob allows users to select their date of birth using a date picker and the button uses onclick="calculateAge()" to run the JavaScript age calculation function when clicked, this <div> with the ID result is used to display validation messages and the calculated age in years, months, and days. Finally, the script.js file is loaded at the bottom of the <body> so JavaScript can access the HTML elements and provide the Age Calculator functionality.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Age Calculator</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="calculator">
<h2>Age Calculator</h2>
<label for="dob">Select your Date of Birth</label>
<input type="date" id="dob" />
<button onclick="calculateAge()">Calculate Age</button>
<div class="result" id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS Code
CSS controls the appearance and layout of the Age Calculator. The universal * selector applies box-sizing: border-box and the Segoe UI font to all elements. The body uses Flexbox with justify-content and align-items to center the calculator vertically and horizontally on the page.
The .calculator class creates the main white card by adding a fixed width, padding, rounded corners, centered text, and a box shadow, input is styled with full width, padding, margins, borders, and rounded corners, while the button uses a full width layout, background color, white text, and cursor: pointer.
Finally, the .result class adds spacing, font size, and font weight so the calculated age or validation message is clearly displayed below the button.
* {
box-sizing: border-box;
font-family: "Segoe UI", sans-serif;
}
body {
min-height: 100vh;
background: #042453; /* DO NOT CHANGE */
display: flex;
justify-content: center;
align-items: center;
}
.calculator {
background: #ffffff;
width: 320px;
padding: 25px;
border-radius: 12px;
text-align: center;
box-shadow: 0 15px 30px rgba(0,0,0,0.2);
}
h2 {
margin-bottom: 15px;
}
label {
font-size: 14px;
}
input {
width: 100%;
padding: 10px;
margin: 10px 0;
border-radius: 6px;
border: 1px solid #ccc;
}
button {
width: 100%;
padding: 10px;
border: none;
border-radius: 6px;
background: #4f46e5;
color: white;
cursor: pointer;
}
.result {
margin-top: 15px;
font-size: 14px;
font-weight: 600;
}
Javascript Code
JavaScript handles the age calculation. The calculateAge() function first gets the selected date of birth from the dob input and selects the result element. If no date is selected, it displays a red validation message and stops the function using return.
Next, JavaScript creates Date objects for the user’s date of birth and the current date. It also checks whether the selected date is in the future and displays an error message if it is invalid. The code then calculates the difference in years, months, and days.
If the day difference is negative, the code adjusts the months and adds the correct number of days from the previous month. Similarly, if the month difference is negative, it adjusts the years and months. Finally, the result is displayed in green using innerText, showing the user’s exact age in years, months, and days.
function calculateAge() {
const dobInput = document.getElementById("dob").value;
const result = document.getElementById("result");
if (!dobInput) {
result.style.color = "red";
result.innerText = "Please select your date of birth";
return;
}
const dob = new Date(dobInput);
const today = new Date();
if (dob > today) {
result.style.color = "red";
result.innerText = "Date of birth cannot be in the future";
return;
}
let years = today.getFullYear() - dob.getFullYear();
let months = today.getMonth() - dob.getMonth();
let days = today.getDate() - dob.getDate();
if (days < 0) {
months--;
days += new Date(today.getFullYear(), today.getMonth(), 0).getDate();
}
if (months < 0) {
years--;
months += 12;
}
result.style.color = "green";
result.innerText = `You are ${years} years, ${months} months, and ${days} days old.`;
}
Related Projects
Day 16 : Shopping Cart (Add / Remove / Total)
Interactive cart with real-time item management and total calculation.
Concepts: Cart state handling, dynamic price calculation, user interaction logic.
Day 20 : Form Auto-Save (Local Storage)
Automatically saves form input data and restores it on reload.
Concepts: LocalStorage usage, input event handling, persistent UI state.
Day 21 : Country Info Finder (API)
Fetches and displays real-time country information using a public REST API.
Concepts: API integration, fetch API, async data handling, dynamic UI rendering.