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:
var date1 = $('#firstPayDate');
var date2 = $('#loanTrm');
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffMonths = Math.ceil(timeDiff / (1000 * 3600 * 24));
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.)