<!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>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
}
.container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
label {
display: block;
margin-bottom: 8px;
font-weight: bold;
}
input[type="date"] {
padding: 8px;
width: 100%;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px 20px;
margin-top: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
#result {
font-weight: bold;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<h2>Age Calculator</h2>
<label for="birthdate">Enter your birthdate:</label>
<input type="date" id="birthdate">
<button onclick="calculateAge()">Calculate Age</button>
<div id="result"></div>
</div>
<script>
function calculateAge() {
const birthdateInput = document.getElementById("birthdate");
const birthdate = new Date(birthdateInput.value);
const now = new Date();
// Calculate the difference in milliseconds between the birthdate and current date
const ageInMillis = now - birthdate;
// Calculate the age in years, months, and days
const years = Math.floor(ageInMillis / (365.25 * 24 * 60 * 60 * 1000));
const months = Math.floor((ageInMillis % (365.25 * 24 * 60 * 60 * 1000)) / (30.44 * 24 * 60 * 60 * 1000));
const days = Math.floor((ageInMillis % (30.44 * 24 * 60 * 60 * 1000)) / (24 * 60 * 60 * 1000));
// Display the result
const resultElement = document.getElementById("result");
resultElement.textContent = `Your age is ${years} years, ${months} months, and ${days} days.`;
}
</script>
</body>
</html>
**
This code creates a simple web page with an input field where the user can enter their birthdate. When they click the "Calculate Age" button, it will display their age in years, months, and days below the button. The age is calculated using JavaScript by subtracting the birthdate from the current date and then converting the difference to years, months, and days. The layout is styled using CSS for a clean and professional look.**
Top comments (0)