Science Stream Practicals

Std 12th IT Subject - Skill Oriented Practical (Science Stream)

SOP 7: Write a JavaScript function to get difference between two dates in days.

Create a page in HTML that contains input box to accept date from user. The input boxes should be used by users to enter their date of birth in the format dd-mm-yyyy. Do not make use of any dropdown boxes.

Source Code: index.html

<!DOCTYPE html>
<html>
<head>
    <title>Date Difference Calculator</title>
</head>
<body>
    <h2>Difference Between Two Dates (in Days)</h2>

    <form name="f1">
        Enter First Date:<input type="date" name="date1"><br><br>
        Enter Second Date:<input type="date" name="date2"><br><br>
        <input type="button" value="Calculate Difference" onclick="calculateDifference()">
    </form>

    <script>
        function calculateDifference() {
            var d1 = f1.date1.value;
            var d2 = f1.date2.value;
            if (d1 === "" || d2 === "") {
                alert("Please enter both dates.");
            }
            // Convert input values to Date objects
            let date1 = new Date(d1);
            let date2 = new Date(d2);
            // Difference in milliseconds
            let diffMs = Math.abs(date2 - date1);
            // Convert to days
            let diffDays = diffMs / (1000 * 60 * 60 * 24);
            alert("Difference between dates: " + diffDays + " days");
        }
    </script>
</body>
</html>

Live Preview