How to get no of months using jquery between the given dates

Last Reply 3 days ago By dharmendr

Posted 5 days ago

I have two date text-box fields one field is for start date and another field is for end date now if i give the below inputs which is not working with my below code how can i get it

var $startdate= new Date('09/01/2019')
var $enddate = new Date('10/02/2019')
var $months = $enddate.getMonth() - $startdate.getMonth() + (12 * ($enddate.getFullYear() - $startdate.getFullYear()));

Below is my expected output

Start Date(mm/dd/yyyy) End Date(mm/dd/yyyy) (Expected)Output   (Present)output
08/28/2019                09/02/2019             2                    1
06/01/2019                09/02/2019             4                    3

 

You are viewing reply posted by: pandeyism 4 days ago.
Posted 4 days ago Modified on 4 days ago

Hi kavithav,

Refer below sample

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#datepicker1").datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: "mm-d-y"
            });
            $("#datepicker2").datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: "mm-d-y"
            });
        });
        function MonthDifference(d1, d2) {
            var months;
            months = (d2.getFullYear() - d1.getFullYear()) * 12;
            months -= d1.getMonth();
            months += d2.getMonth();
            return months <= 0 ? 0 : months;
        }
        function cal() {
            d1 = new Date($("#datepicker1").val());
            d2 = new Date($("#datepicker2").val());
            alert("The difference between two dates is: " + MonthDifference(d1, d2));
        }
    </script>
</head>
<body>
    <div>
        <p>
            Date1:
            <input type="text" id="datepicker1"></p>
        <p>
            Date2:
            <input type="text" id="datepicker2"></p>
        <button id="calculate" onclick="cal()">
            Calculate
        </button>
    </div>
</body>
</html>

Screenshot