0

I need to find number of days between 2 selected dates. I have tried the following code but it returns error results for some dates.

function getDateObject(str) {
  var arr = str.split("-");
  return new Date(arr[0], arr[1], arr[2]);
}

$('#from_date,#to_date').bind("change paste keyup", function() {
    var date1 = getDateObject($('#from_date').val());
    var date2 = getDateObject($('#to_date').val());
    var days = (date2 - date1) / 86400000;
    alert(days); //it returns -1 for from:2016-01-31 - to:2016-02-01.
    //other dates like from:2016-01-13 - to:2016-01-14 returns 1 correctly
}

please help me to resolve this issue.

Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59

2 Answers2

0

You need to parse your dates correctly, currently:

new Date("2016", "01", "31");

will give

Wed Mar 02 2016 00:00:00 GMT+0530 (IST)

Just this will work fine

// str should be in yy-mm-dd
function getDateObject(str) {
  return new Date(str);
}
void
  • 36,090
  • 8
  • 62
  • 107
0

finally I found a solution.

function getDateObject(str) {
  var arr = str.split("-");
  return new Date(arr[0], arr[1]-1, arr[2]);//just added -1 in arr[1] that is month.
}

$('#from_date,#to_date').bind("change paste keyup", function() {
    var date1 = getDateObject($('#from_date').val());
    var date2 = getDateObject($('#to_date').val());
    var days = (date2 - date1) / 86400000;
    alert(days); 
}

this gave me the output I needed.

Thanks you all tried to help me.

Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59