Age Calculator Code Snippet (HTML/CSS/JS)

age calculator

Certainly, here’s the complete age calculator code implemented in HTML, CSS, and JavaScript:

HTML Code

<html>
<head>
    <title>Age Calculator</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>Age Calculator</h1>
        <label for="birthdate">Enter your birthdate:</label>
        <input type="date" id="birthdate">
        <button id="button_calculate">Calculate</button>
        <p id="result"></p>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS Code

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
.container {
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    padding: 20px;
    text-align: center;
}
h1 {
    color: #333;
}
label {
    font-weight: bold;
}
input[type="date"] {
    padding: 8px;
    width: 100%;
}
button_calculate {
    background-color: #007bff;
    color: #fff;
    border: none;
    padding: 10px 20px;
    margin-top: 10px;
    border-radius: 5px;
    cursor: pointer;
}
p {
    margin-top: 10px;
}

Javascript Code:

document.getElementById("calculate").addEventListener("click", function () {
    const birthdate = new Date(document.getElementById("birthdate").value);
    const today = new Date();

    if (isNaN(birthdate)) {
        alert("Please select a valid date.");
        return;
    }

    const ageInMilliseconds = today - birthdate;

    const ageInYears = Math.floor(ageInMilliseconds / 31557600000); // 1 year = 31,556,952,000 milliseconds

    const birthMonth = birthdate.getMonth();
    const currentMonth = today.getMonth();
    let ageInMonths = currentMonth - birthMonth;

    if (today.getDate() < birthdate.getDate()) {
        ageInMonths--;
    }

    if (ageInMonths < 0) {
        ageInMonths = ageInMonths + 12;
    }

    const birthDay = birthdate.getDate();
    const currentDay = today.getDate();

    if (currentDay < birthDay) {
        const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 0).getDate();
        ageInMonths--;
        ageInDays = lastDayOfMonth - birthDay + currentDay;
    } else {
        ageInDays = currentDay - birthDay;
    }

    const result = `Your age is approximately ${ageInYears} years, ${ageInMonths} months, and ${ageInDays} days.`;
    document.getElementById("result").innerHTML = result;
});

Get the Online Demo

Leave a Reply

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