4

I was wanting to retrieve the month differences between two dates that a user enters in using the bootstrap datepicker. Along with this I am also trying to replace the second value (date2) to what the difference in months is when the user clicks the calculate button. When trying to work on this my code does not seem to be working...

Here is what I have so far:

$('#clickMe').click(function() {
    var date1 = $('#firstPayDate');
    var date2 = $('#loanTrm');
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var diffMonths = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
    date2.val(date2.val().replace(diffMonths));
});

Here is a picture demonstration of what I am trying to accomplish:

enter image description here

I am trying to take the difference between these two entries (Maturity Date - First payment date)

enter image description here I am trying to get the calculations to occur once the user clicks the Calculate button, the difference in months gets replaced with the value that was entered in Maturity Date.

Any help will be greatly appreciated!

Alex111
  • 167
  • 1
  • 4
  • 14
  • No replacement string appear provided to `.replace()` at `date2.val().replace(diffDays)` ? – guest271314 Jan 20 '16 at 15:04
  • 1
    I believe date1 and date2 are just a jQuery wrappers around HTMLElement. Why are you expecting a Date object here? Could you provide jsfiddle example of what you're trying to accomplish? – Microfed Jan 20 '16 at 15:04
  • 1
    For any date stuff I always turn to http://momentjs.com/ – ED-209 Jan 20 '16 at 15:04
  • those are jQuery objects ....not date objects – charlietfl Jan 20 '16 at 15:04
  • Can create stacksnippets to demonstrate ? – guest271314 Jan 20 '16 at 15:06
  • Based on the added image: looks like you're not trying to find the difference between dates, you're trying to add an integer number of months (from Maturity Date) to a date (First Payment Date) -- is that correct? If so, this is a duplicate of http://stackoverflow.com/questions/2706125/javascript-function-to-add-x-months-to-a-date – Daniel Beck Jan 20 '16 at 15:17
  • Yes that is right. Basically if a user enters their maturity date as March 4, 2015 and their first payment date as January 4, 2015, and when they click the calculate button, I want the differences in months to replace the date in the Maturity date box (which is 3). – Alex111 Jan 20 '16 at 15:19
  • Wait. You said I was right, then described the opposite of what I said (and what your screenshot shows.) Is the user entering a date in Maturity Date which you want to convert into a number of months, or are they entering a number of months which you want to convert into a date? – Daniel Beck Jan 20 '16 at 15:21
  • They are entering a date in Maturity date in mm/dd/yyyy format, which I want to take the difference between that and the first payment date in months. Sorry for the confusion. – Alex111 Jan 20 '16 at 15:25
  • I believe a similar question has been answered [here](http://stackoverflow.com/questions/10225268/how-do-i-find-the-difference-between-two-dates-using-jquery). – James J. Hill Jan 20 '16 at 15:29

4 Answers4

6

Below logic will get difference in months

(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())
Anoop Isaac
  • 932
  • 12
  • 15
5

The human calendar is not conducive to easy math -- fortunately javascript provides a Date object which does most of the dirty work for us.

This will convert the date strings into Date objects (glossing over any formatting or validation issues with the input fields' contents. Note in your particular case that since you intend to replace #loanTrm's value with a number of months instead of a date, this will break if the user hits "calculate" twice; correcting that is more of a user interface issue than a coding issue so I'll ignore it for the time being):

var date1 = new Date($('#firstPayDate').val());
var date2 = new Date($('#loanTrm').val());
var datediff = date2 - date1; 

(As pointed out in comments below, note also that Date uses the user's locale to determine the expected date format: if you're always displaying dates in mm/dd/yy, well, you probably shouldn't do that, because much of the world uses dd/mm/yy. You'll either need to format the input field based on user locale as well, or else construct your Dates with the more explicit new Date(year, month, day, hours, minutes, seconds, milliseconds) instead of the string shortcut I showed above.) (Like I said: dates are hard! Wait until you try timezones, they're even more fun)

datediff now contains the real difference (in milliseconds) between the two dates.

What happens next depends on what you exactly mean by "the difference in months", because months aren't always the same length.

If you don't care about precision, you can get a probably-close-enough approximation by pretending every month has thirty days and dividing datediff by (1000*60*60*24*30). If you do care about precision, you've moved out of roll-your-own territory and probably ought to use one of the libraries devoted to this kind of math (momentjs is a good one.)

(There are many other SO questions covering this type of thing; any answer in any of them that depends on string matching instead of Date() is going to be wrong at least once every four years, and probably much more often that.)

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
  • A problem that occurs only once every 4 years is a really *fun* problem to try to solve. If the sarcasm wasn't laid on thick enough, really *really* fun problem. – Neil Jan 20 '16 at 15:47
  • If the dates are always printed in mm/dd/yyyy, then `new Date()` is guaranteed to fail for users with locales that use a different format. – coladict Jan 20 '16 at 15:51
-2

Try erasing your value

date2.val();  

then assign the value to your input.

date2.val(diffMonths);
jasmo2
  • 525
  • 7
  • 13
-2

Try this. You can check the difference of months in the code snippet.

  $(function() {
// you can change the format to the way you want

                        $( "#datepicker1" ).datepicker({
                            yearRange: "-20:+100",
                            changeMonth: true,
                            changeYear: true,
                            dateFormat: "d-M-y"
                        });
                


                        $( "#datepicker2" ).datepicker({
                            yearRange: "-20:+100",
                            changeMonth: true,
                            changeYear: true,
                            dateFormat: "d-M-y"
                        });
});


function monthDiff(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: " +monthDiff(d1, d2));
}
<script 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>
<p>Date1: <input type="text" id="datepicker1"></p>
<p>Date2: <input type="text" id="datepicker2"></p>
<button id="calculate" onclick="cal()"> Calculate </button>
HookUp
  • 393
  • 1
  • 6
  • 20