Reputation: 167
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:
I am trying to take the difference between these two entries (Maturity Date - First payment date)
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!
Upvotes: 4
Views: 15493
Reputation: 942
Below logic will get difference in months
(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())
Upvotes: 6
Reputation: 413
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>
Upvotes: -2
Reputation: 21505
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.)
Upvotes: 5
Reputation: 525
Try erasing your value
date2.val();
then assign the value to your input.
date2.val(diffMonths);
Upvotes: -2