0

I have a script where i want to count the number of months between 2 dates. This is what I have tried

    var dateTo = document.getElementById("date1").value;
    var d2 = dateTo.split("-");
    var date1 =  new Date(d2[2], parseInt(d2[1]) - 1, d2[0]);
    var date2 = new Date(2019, 12, 31);
    var year1 = date1.getFullYear();
    var year2 = date2.getFullYear();
    var month1 = date1.getMonth();
    var month2 = date2.getMonth();
    if (month1 === 0) { 
        month1++;
        month2++;
    }
    var numberOfMonths = (month2 - month1);

The idea is that a user picks a date from an input calender and it count the amount of months left between the chosen date until the end of the current year.

The result I'm getting if i write down the date 2019-05-13 it returns -4 months, which is the wrong result and I'm unsure on what I'm doing wrong.

pancake
  • 590
  • 7
  • 24

1 Answers1

1

The idea is that a user picks a date from an input calender and it count the amount of months left between the chosen date until the end of the current year.

You can achieve that in a more simpler way:

$('#datepicker').datepicker({
  onSelect: function() { 
    var date = $(this).datepicker('getDate'); // get the date chosen
    var month = date.getMonth(); // get the month
    var monthsLeft = 11 - month; // get the differences, months are 0 based
    console.log('Month Left:', monthsLeft);
  }
});
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Date: <input type="text" id="datepicker"></p>
Mamun
  • 66,969
  • 9
  • 47
  • 59