Reputation: 1387
I have a form that has two date fields. I am trying to select the dates from the two inputs and compare them with JQuery. The problem I am having is that it returns NaN
.
I think might be because the typeof
on the dates returns strings.
$('#id_date_completed').change(function() {
date_received = $("#id_date_received").val();
date_completed = $("#id_date_completed").val();
var diff = date_completed - date_received;
var days = diff / 1000 / 60 / 60 / 24;
console.log(days);
}
EDIT
My question differs from Get difference between 2 dates in javascript? as I am using bootstrap-datepicker library. Arun P Johny answer was perfect
Upvotes: 3
Views: 9216
Reputation: 388406
The problem is .val()
will return a string so both date_received
and date_completed
are string values so subtracting them will return NaN
.
Instead you can use the getDate() method of the bootstrap-datepicker
$("#id_date_received, #id_date_completed").datepicker();
$('button').click(function() {
var date_received = $("#id_date_received").datepicker('getDate');
var date_completed = $("#id_date_completed").datepicker('getDate');
var diff = date_completed - date_received;
var days = diff / 1000 / 60 / 60 / 24;
$('span').text(days)
})
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>
<input id="id_date_received" />
<input id="id_date_completed" />
<button>Test</button>
<span></span>
Upvotes: 7