Age Calculator Source Code

Age Calculator Using HTML, CSS and JavaScript (Free Source Code)

Determining an exact age reliably is a valuable resource in site development, especially in services that differentiate between certain ages. I’m happy to give you a free source code for Age Calculator Using HTML, CSS, and JavaScript; it’s more efficient to use, and a simple yet effective way to calculate the age instantly. This code is very simple and can be modified to fit any project or construct.

GitHub Source: Age Calculator Source Code

Features

  • Dynamic Dropdowns for Date Selection: Updates the day options depending on the selected month and year and also supports Leap year.
  • Multiple Age Units: Shows the age in years, months, weeks, days, hours, minutes, and seconds.
  • Automatic Default Dates: ‘Date of Birth’ and “Age-as-of” pre-fill with default and current age.
  • Real-Time Input Validation and Calculation: Validates inputs for age and avoids the need to refresh the page in order to display the results.
  • Responsive and User-Friendly Interface: Clean and simple to use with easy date picking and aesthetically pleasing styling.
  • Easy to Customize: This application makes it easier to change the layout and style of the page and its functionality in order to suit the project.
  • Compatibility: Integrated nicely with all current browsers as well as with the majority of Content Management Systems such as WordPress.
  • Clean Code: The organized and well commented code permits the appropriate reading and feasible use.

Technologies Used

  • HTML (Hypertext Markup Language)
  • CSS (Cascading Style Sheets)
  • JS (JavaScript)

Recommended for You

Video Tutorial

Steps to Build Sidebar Menu

  • Create Project Folder: First of all, create the folder for the project files only.
  • Create index.html with CSS and JS code: To use this in your project you have to write HTML, CSS, and JavaScript code in your project.
  • Copy & Paste the Code Below: Use the code given below and modify it to your need.

Age Calculator Source Code

Here is the HTML code for your index.html file:

<!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;
            margin: 0;
            padding: 0;
            background-color: #f4f4f9;
            color: #333;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            font-weight: 600;
        }

        .panel {
            background: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 4px 8px 50px rgba(0, 0, 0, 0.4);
            width: 100%;
            max-width: 600px;
        }

        h1 {
            text-align: center;
            margin-bottom: 20px;
            font-size: 24px;
        }

        form {
            display: grid;
            gap: 15px;
        }

        .form-group {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .form-group label {
            font-size: 14px;
            width: 30%;
        }

        .dob-fields, .age-at-fields {
            display: flex;
            justify-content: space-between;
            width: 100%;
        }

        .dob-fields select, .dob-fields input[type="number"],
        .age-at-fields select, .age-at-fields input[type="number"] {
            width: 28%;
            padding: 8px;
            font-size: 14px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        input[type="submit"] {
            padding: 10px 20px;
            background: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 18px;
            font-weight: 700;
        }

        input[type="submit"]:hover {
            background: #0056b3;
        }

        .result {
            margin-top: 20px;
            padding: 10px;
            background: #f1f4fd;
            border: 2px solid green;
            border-radius: 5px;
            color: green;
            width: 96%;
            height: 200px;
            display: flex;
            flex-direction: column;
            justify-content: space-evenly;
            font-size: 16px;
            overflow-y: auto;
        }

        .result p {
            margin: 0;
            font-size: 16px;
        }

        .age-bold {
            font-weight: bold;
            color: #720340;
        }

        
    </style>
    <script>
        // Days in each month, index 0 is January, index 1 is February, etc.
        const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        
        // Function to update the number of days based on selected month and year
        function updateDays(selectId) {
            const selectElement = document.querySelector(`#${selectId}`);
            const month = parseInt(document.querySelector(`#${selectId.replace('-day', '-month')}`).value) - 1; // Get the selected month (0-indexed)
            const year = parseInt(document.querySelector(`#${selectId.replace('-day', '-year')}`).value);
            
            // Clear existing options
            selectElement.innerHTML = '';
            
            // Get the correct number of days for the selected month
            let days = daysInMonth[month];
            
            // February (index 1) in a leap year
            if (month === 1) {
                if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
                    days = 29; // Leap year
                }
            }

            // Add day options dynamically
            for (let i = 1; i <= days; i++) {
                const option = document.createElement("option");
                option.value = i;
                option.textContent = i;
                selectElement.appendChild(option);
            }
        }

        // Function to calculate the age and different time formats
        function calculateAge(event) {
            event.preventDefault();

            // Get Date of Birth (DOB) and Age-at date values
            const dobMonth = parseInt(document.querySelector("#dob-month").value);
            const dobDay = parseInt(document.querySelector("#dob-day").value);
            const dobYear = parseInt(document.querySelector("#dob-year").value);
            const ageAtMonth = parseInt(document.querySelector("#ageAt-month").value);
            const ageAtDay = parseInt(document.querySelector("#ageAt-day").value);
            const ageAtYear = parseInt(document.querySelector("#ageAt-year").value);

            // Validate input
            if (isNaN(dobMonth) || isNaN(dobDay) || isNaN(dobYear) || isNaN(ageAtMonth) || isNaN(ageAtDay) || isNaN(ageAtYear)) {
                alert("Please enter valid dates.");
                return;
            }

            // Create Date objects for DOB and Age-at Date
            const dob = new Date(dobYear, dobMonth - 1, dobDay); // months are 0-indexed in JavaScript
            const ageAtDate = new Date(ageAtYear, ageAtMonth - 1, ageAtDay);

            // Calculate age
            let years = ageAtDate.getFullYear() - dob.getFullYear();
            let months = ageAtDate.getMonth() - dob.getMonth();
            let days = ageAtDate.getDate() - dob.getDate();

            // Adjust if days or months are negative
            if (days < 0) {
                months--;
                days += new Date(ageAtDate.getFullYear(), ageAtDate.getMonth(), 0).getDate(); // Get last day of previous month
            }

            if (months < 0) {
                years--;
                months += 12;
            }

            // Calculate total months, weeks, and other units
            const totalDays = Math.floor((ageAtDate - dob) / (1000 * 60 * 60 * 24)); // Total days
            const totalMonths = Math.floor(totalDays / 30.44); // Average days per month
            const totalWeeks = Math.floor(totalDays / 7); // Total weeks
            const totalHours = totalDays * 24; // Total hours
            const totalMinutes = totalHours * 60; // Total minutes
            const totalSeconds = totalMinutes * 60; // Total seconds

            // Calculate age in months, weeks, and days separately
            const monthsAndDays = `${totalMonths} months, ${Math.floor((totalDays % 30.44) / 7)} week(s), and ${totalDays % 7} day(s)`;
            const weeksAndDays = `${totalWeeks} week(s) and ${totalDays % 7} day(s)`;

            // Display results
            document.querySelector("#result").innerHTML = `
                <p class="age-bold">Age as of the selected date: ${years} years ${months} months ${days} days</p>
                <p><strong>Age in Months:</strong> ${monthsAndDays}</p>
                <p><strong>Age in Weeks:</strong> ${weeksAndDays}</p>
                <p><strong>Age in Days:</strong> ${totalDays} days</p>
                <p><strong>Age in Hours:</strong> ${totalHours} hours</p>
                <p><strong>Age in Minutes:</strong> ${totalMinutes} minutes</p>
                <p><strong>Age in Seconds:</strong> ${totalSeconds} seconds</p>
            `;
        }

        // Set default values for Date of Birth and current Age-at date
        window.onload = function() {
            // Set default Date of Birth (8 June 1981)
            document.querySelector("#dob-month").value = 6;
            document.querySelector("#dob-day").value = 8;
            document.querySelector("#dob-year").value = 1981;
            updateDays("dob-day"); // Update days for default month (June)

            // Set Age-as-of date to current date
            const currentDate = new Date();
            document.querySelector("#ageAt-month").value = currentDate.getMonth() + 1; // 0-indexed month
            document.querySelector("#ageAt-day").value = currentDate.getDate();
            document.querySelector("#ageAt-year").value = currentDate.getFullYear();
            updateDays("ageAt-day"); // Update days for the current month
        };
    </script>
</head>
<body>

<div class="panel">
    <h1>Age Calculator</h1>
    <form onsubmit="calculateAge(event)">
        <div class="form-group">
            <label for="dob-month">Date of Birth:</label>
            <div class="dob-fields">
                <select id="dob-month" onchange="updateDays('dob-day')">
                    <option value="1">January</option>
                    <option value="2">February</option>
                    <option value="3">March</option>
                    <option value="4">April</option>
                    <option value="5">May</option>
                    <option value="6">June</option>
                    <option value="7">July</option>
                    <option value="8">August</option>
                    <option value="9">September</option>
                    <option value="10">October</option>
                    <option value="11">November</option>
                    <option value="12">December</option>
                </select>

                <select id="dob-day">
                    <!-- Days will be populated here based on selected month -->
                </select>

                <input type="number" id="dob-year" placeholder="Year" min="1900" onchange="updateDays('dob-day')" />
            </div>
        </div>

        <div class="form-group">
            <label for="ageAt-month">Age as of:</label>
            <div class="age-at-fields">
                <select id="ageAt-month" onchange="updateDays('ageAt-day')">
                    <option value="1">January</option>
                    <option value="2">February</option>
                    <option value="3">March</option>
                    <option value="4">April</option>
                    <option value="5">May</option>
                    <option value="6">June</option>
                    <option value="7">July</option>
                    <option value="8">August</option>
                    <option value="9">September</option>
                    <option value="10">October</option>
                    <option value="11">November</option>
                    <option value="12">December</option>
                </select>

                <select id="ageAt-day">
                    <!-- Days will be populated here based on selected month -->
                </select>

                <input type="number" id="ageAt-year" placeholder="Year" min="1900" onchange="updateDays('ageAt-day')" />
            </div>
        </div>

        <input type="submit" value="Calculate Age" />
    </form>

    <div id="result" class="result"></div>
</div>

</body>
</html>

Download Source Code

Get this fully working Age Calculator Using HTML CSS n JavaScript to use without any copyright issues. Follow the button below to download and use it in your projects.

Conclusion

We offer you this Age Calculator Using HTML, CSS, and JavaScript, an app that will be perfect for your website and applications. This source code helps save time or you direct your efforts to other features.

When using this code, it is kindly requested to link back to JV Source Codes website. Do not forget to subscribe to our recently created YouTube channel for more tutorials or leave a comment if you have any problems. I’ll be happy to help!

Download JV Source Codes

Similar Posts

Leave a Reply

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