-1

I am trying to get number of Days between 2 Dates, I have searched this on net and found pretty good solution..but when i apply this, its giving me NaN. I am unable to understand whats wrong in this code, Kindly check it and guide me what i am doing wrong here,

HTML CODE

<input id="date_from" class="form-control input-sm" type="text" name="date_from" required>

<input id="date_to" class="form-control input-sm" type="text" name="date_to" required>

JS CODE

function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}   

function daydiff(first, second) {
    return Math.round((second-first)/(1000*60*60*24));
} 

$(document).ready(function(){
    $("#date_to").change(function(){        
        alert(daydiff(parseDate($("#date_from").val())- parseDate($("#date_to").val())));
        alert($("#date_from").val());
    });
});

Output

Nan

dev90
  • 7,187
  • 15
  • 80
  • 153
  • Duplicate of http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript. – Sébastien Vercammen Feb 29 '16 at 20:39
  • forgot to use your `parseDate()` function and you are trying to do calculation on strings. Suggest you use datepickers and avoid needing to do a lot of validation yourself. Use browser console to check errors – charlietfl Feb 29 '16 at 20:40
  • Function daydiff accepts two parameters, and you're only passing one. – Tony Feb 29 '16 at 20:42

1 Answers1

1

You substract dates as strings which is NaN, try this:

function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}   

function daydiff(first, second) {
    return Math.round((parseDate(second).valueOf()-parseDate(first).valueOf())/(1000*60*60*24));
} 

$(document).ready(function(){
  $("#date_to").change(function(){        
    alert(daydiff($("#date_from").val(), $("#date_to").val()));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="date_from">From:</label>
<input type="text" id="date_from"/>
<br/>
<label for="date_to">To:</label>
<input type="text" id="date_to"/>
jcubic
  • 61,973
  • 54
  • 229
  • 402