0

I want to calculate the difference between two dates but the result I get is NaN, this is my code:

 var date1 = $("#dateb").val();
 var date2 = $("#datea").val();
 var date_difference = parseInt((date1-date2)/(24*3600*1000));
 alert(date_difference);  // NaN

Notice in my datepicker I am using this format:

$('.datePicker').datepicker({
   format: 'yyyy/mm/dd'
{);
buydadip
  • 8,890
  • 22
  • 79
  • 154
C.Azzeddine
  • 25
  • 2
  • 7
  • 1
    You would need to convert the text to an actual Date() object first... – Steve Nov 02 '17 at 11:50
  • 1
    Moment.js is a good library for manipulating dates easily. https://momentjs.com/ – Steve Nov 02 '17 at 11:51
  • first search https://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript – Álvaro Touzón Nov 02 '17 at 12:03
  • 1
    Possible duplicate of [Get difference between 2 dates in JavaScript?](https://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript) – MUlferts Nov 02 '17 at 12:13

4 Answers4

1

Your issue is that you must convert the dates into Date objects before subtracting them:

var date1 = new Date($("#dateb").val());
var date2 = new Date($("#datea").val());
var date_difference = Math.ceil((date2 - date1) / (1000 * 60 * 60 * 24));
buydadip
  • 8,890
  • 22
  • 79
  • 154
0

i didnt see how is the val of both inputs, expecting goes in this match MM-dd-yyy", this is an aproximation of would be:

var date1 = +new Date(2017,1,9).getTime();
var date2 = +new Date('09-10-2017').getTime();
var date_difference=(date1-date2)/(24*3600*1000);
console.log(date1, date2, new Date(date_difference));

Expect it help you

buydadip
  • 8,890
  • 22
  • 79
  • 154
Álvaro Touzón
  • 1,247
  • 1
  • 8
  • 21
0

Here is a snippet with a working example from another SO question. Just run the snippet below to see how it returns a count of days for the difference between the two dates:

var date1 = new Date("7/13/2017");
var date2 = new Date("12/15/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays);
MUlferts
  • 1,310
  • 2
  • 16
  • 30
-1

Try this,

first, convert into date

function parseDate(input) {
    // Transform date from text to date
    var parts = input.match(/(\d+)/g);
    // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
    return new Date(parts[0], parts[1] - 1, parts[2]); // months are 0-based
}
var date1 = parseDate($("#dateb").val());
var date2 = parseDate($("#datea").val());
var diff = date1 - date2 ; 
var date_difference=parseInt(diff /(24*3600*1000));
alert(date_difference);
Sanyami Vaidya
  • 799
  • 4
  • 21