Open In App

Age Calculator Design using HTML CSS and JavaScript

Last Updated : 16 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Age Calculator, we will take the date of birth as the date input on the page and print the age from that input. We will create the structure using HTML and design it with CSS. JavaScript will be used to implement and show the output.

Approach

  • Create the Calculator structure using an HTML input tag for date input and a submit button.
  • Style the structure with CSS using classes and elements.
  • In JavaScript,
    • Input Retrieval and Conversion:
      • The getDOB function retrieves the input Date of Birth (DOB) from an HTML input element, converts it to a usable format, and also retrieves the current date.
    • Age Calculation:
      • The code calculates the age difference in years, months, and days by comparing the input DOB with the current date. It handles cases where the input date is invalid and adjusts the age calculation accordingly.
    • Output Display:
      • The calculated age is displayed as output on the HTML page. If the input date is invalid, an “Invalid Date” message is shown.
    • Default Date Setting:
      • The currentDate function sets the default date value for the current date in a specified format using the formatted function.
    • Date Formatting Utility:
      • The formatted function takes a date object (defaulting to the current date) and formats it as YYYY-MM-DD. The short function ensures that the month and day components are zero-padded to two digits.

Example: This example describes the basic implementation of the Age Calculator using HTML, CSS, and Javascript.

Javascript




// Define funtion to get calculated Age
function getDOB() {
 
    // Getting input from html input element
    let data =
        document.getElementById("inputDob").value;
 
    // Convert input data to usable format
    // as day,month and year
    let dob = new Date(data);
    let day = dob.getDate();
    let month = dob.getMonth();
    let year = dob.getFullYear();
 
    // Getting current date and calculating the difference
    let now =
        new Date(document.getElementById("cdate").value);
    console.log(now);
    let yearDiff = now.getFullYear() - year;
    let monthDiff = now.getMonth() - month;
    let dateDiff = now.getDate() - day;
 
    // Calculating the Age
    if (yearDiff < 0) console.log("invalid date");
    else if (monthDiff > 0) {
        console.log(yearDiff);
    } else if (monthDiff === 0 && dateDiff >= 0) {
        console.log(yearDiff);
    } else {
        yearDiff = yearDiff - 1;
        if (monthDiff <= 0)
            if (dateDiff > 0) monthDiff = 12 + monthDiff;
            else monthDiff = 11 - monthDiff;
    }
    if (dateDiff < 0) {
        dateDiff = 30 + dateDiff;
        monthDiff -= 1;
    }
 
    // Show calculated age as output
    // and invalid if wrong input is given
    if (yearDiff < 0)
        document.getElementById("currentAge").innerHTML = "Invalid Date";
    else
        document.getElementById("currentAge").innerHTML =
            "Your current Age is " + yearDiff + " years "
            + monthDiff + " months " + dateDiff + " days";
}
 
// Function to provide default date value
function currentDate() {
    console.log(formatted());
    let d = document.getElementById("cdate");
    d.value = formatted();
}
 
function formatted(date = new Date()) {
    return [
        date.getFullYear(),
        short(date.getMonth() + 1),
        short(date.getDate()),
    ].join("-");
}
function short(num) {
    return num.toString().padStart(2, "0");
}
 
// Calling current date function to set default date value
currentDate();


HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Age Calculator</title>
    <link rel="stylesheet"
          href="style.css" />
</head>
 
<body>
    <div class="card">
        <header>
            <h1>AGE CALCULATOR</h1>
        </header>
 
        <div>
            <label>Enter your Date of Birth</label>
 
            <input id="inputDob"
                   type="date"
                   value="2000-01-01" />
        </div>
        <br />
 
        <!-- Take the date from which age is to be calculated -->
        <div>
            <label>Current Date</label><br>
            <input id="cdate"
                   type="date"
                   value="" />
        </div>
        <br />
 
        <button type="button"
                onclick="getDOB()">
            Calculate
        </button>
        <br />
        <div id="currentAge"></div>
        <script src="script.js"></script>
    </div>
</body>
 
</html>


CSS




/* Setting alignment and fonts */
body {
    display: flex;
    text-align: center;
    font-family:
      "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS",
        sans-serif;
}
 
/* Defining card properties */
.card {
    min-width: 30%;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    transition: 0.3s;
    border-radius: 5px;
    margin: auto;
    padding: 2%;
    padding-top: 0%;
}
 
header {
    font-size: larger;
}
 
header h1 {
    background-color: rgb(231, 231, 231);
    color: green;
    font-size: xx-large;
    padding: 1%;
}
 
/* Setting font and margin for text before input box */
label {
    font-size: large;
    margin: 2%;
}
 
button {
    font-size: large;
    padding: 1%;
}
 
input {
    width: 200px;
    height: 50px;
    font-size: larger;
    font-family: Arial, Helvetica, sans-serif;
    text-align: center;
}
 
#inputDob {
    margin: 2%;
}
 
p {
    font-size: larger;
    margin: 5%;
}
 
#currentAge {
    min-width: 30%;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    transition: 0.3s;
    border-radius: 5px;
    margin: auto;
    margin-top: 5%;
    padding: 5%;
    padding-top: 7%;
    font-size: larger;
}


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads