Alex111 Alex111 -3 years ago 148
HTML Question

Get the difference in months between two dates in (mm/dd/yyyy) format using jquery

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));

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!

Answer Source

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download