support@codebucket.net

Calculate years months days between two dates in JavaScript

Calculate years months days between two dates in JavaScript

K. M. Shawkat Zamil | October 01, 2022

Hello Developers,

In this demonstration, I will show you how to calculate years months days between two dates. You can write your own code but I think that this function will help you a lot. Let me show you.

 

First Step: Create two input field

 

In your local computer, create a file named test.php and add two date input fields with a continue button and a field to show the result.

 

<div class="container">
        <div class="form-group">
            <label for="from_date">From Date:</label>
            <input type="date" class="form-control from_date" id="from_date">
        </div>
        <div class="form-group">
            <label for="to_date">To Date:</label>
            <input type="date" class="form-control to_date" id="to_date">
        </div>
        <div class="checkbox">
            <label><input type="checkbox" class="element_checked" id="element_checked"> Continue</label>
        </div>
        <div class="form-group">
            <label for="result">Result:</label>
            <input type="text" class="form-control result" id="result" placeholder="Duration" value="">
        </div>
    </div>

 

Second Step: Create a function to calculate the years months and days 

 

After that add the below function to calculate years months and days.

 

function calcDate(date1, date2) {
            if (date1 > date2) {
                var result = calcDate(date2, date1);
                result.years = -result.years;
                result.months = -result.months;
                result.days = -result.days;
                return result;
            }
            result = {
                years: date2.getYear() - date1.getYear(),
                months: date2.getMonth() - date1.getMonth(),
                days: date2.getDate() - date1.getDate()
            };
            if (result.days < 0) {
                result.months--;
                var copy1 = new Date(date1.getTime());
                copy1.setDate(32);
                result.days = 32 - date1.getDate() - copy1.getDate() + date2.getDate();
            }
            if (result.months < 0) {
                result.years--;
                result.months += 12;
            }

            var message = '';
            message += result.years + " years "
            message += result.months + " months "
            message += result.days + " days "
            return message;
        }

 

Third Step: Final Touch

 

Now we have to read the two input date values, pass the value to the function and show the result in that field. Additionally, a continue button was added to calculate between the first date and today's date. The complete code is given below:

 

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body>

    <div class="container">
        <div class="form-group">
            <label for="from_date">From Date:</label>
            <input type="date" class="form-control from_date" id="from_date">
        </div>
        <div class="form-group">
            <label for="to_date">To Date:</label>
            <input type="date" class="form-control to_date" id="to_date">
        </div>
        <div class="checkbox">
            <label><input type="checkbox" class="element_checked" id="element_checked"> Continue</label>
        </div>
        <div class="form-group">
            <label for="result">Result:</label>
            <input type="text" class="form-control result" id="result" placeholder="Duration" value="">
        </div>
    </div>


    <script>
        $('.from_date, .to_date, .element_checked').bind('change click keyup', function(event) {

            var from_date = $('#from_date').val();
            var to_date = $('#to_date').val();

            from_date = new Date(from_date);
            var element_checked = $('#element_checked').prop('checked');

            if (element_checked == true) {
                var to_date = $('#to_date').val('');
                var to_date = new Date();
                $('#to_date').prop('readonly', true);

            } else {
                $('#to_date').prop('readonly', false);
                if (to_date === '') {
                    var date = new Date();
                    var currentDate = date.toISOString().substring(0, 10);
                    $('#to_date').val(currentDate);

                    to_date = new Date(to_date);
                } else {
                    $('#element_checked').prop('checked', false);
                    to_date = new Date(to_date);
                }
            }
            var message = calcDate(from_date, to_date);
            $('#result').val(message);
        });



        function calcDate(date1, date2) {
            if (date1 > date2) {
                var result = calcDate(date2, date1);
                result.years = -result.years;
                result.months = -result.months;
                result.days = -result.days;
                return result;
            }
            result = {
                years: date2.getYear() - date1.getYear(),
                months: date2.getMonth() - date1.getMonth(),
                days: date2.getDate() - date1.getDate()
            };
            if (result.days < 0) {
                result.months--;
                var copy1 = new Date(date1.getTime());
                copy1.setDate(32);
                result.days = 32 - date1.getDate() - copy1.getDate() + date2.getDate();
            }
            if (result.months < 0) {
                result.years--;
                result.months += 12;
            }

            var message = '';
            message += result.years + " years "
            message += result.months + " months "
            message += result.days + " days "
            return message;
        }
    </script>

</body>

</html>

 

Just turn on your apache and type the below line in the browser and see the magic:

 

http://localhost/test/test.php

 

Hope you might get help in your development journey.

 

Read More: Password Strength check using Regular Expression in JavaScript

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.