2

I've been searching to get the date difference in Javascript, but I am not quite getting the answers I need.

When I compare 2015/12/02 to 2015/11/30, the date difference should be 2. But with my code, I get -28. how do I resolve this issue - also considering the days of the months differ.

    var btdate = new Date('2015/11/30');
    var etdate = new Date('2015/12/02');

    var diff2 = etdate.getDate() - btdate.getDate();
    console.log(diff2);
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • Possible duplicate of [Get difference between 2 dates in javascript?](http://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript) – Buzz Dec 02 '15 at 05:45
  • Date returns the day of the month. So you'd need to factor in the differences between each month – Binvention Dec 02 '15 at 05:46

6 Answers6

0

It is because getDate() just gives you a day number e.g. in your case 30 and 2, so you are getting -28 as difference

if you want to get the number of days between two dates, use getTime() and then convert the difference to days

var diff = etdate.getTime() - btdate.getTime();
var days = diff/1000/60/60/24; // 1000 for milli seconds, 60 for seconds, 60 for minutes, 24 for hours in a day.
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
0

Get the difference in milliseconds and convert it to dates

var btdte = new Date('2015/11/30');
var etdate = new Date('2015/12/02');

//Get time difference in milliseconds
var timeDiff = Math.abs(etdate.getTime() - btdte.getTime());

//Convert milliseconds to dates
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 

console.log(diffDays);
Charlie
  • 22,886
  • 11
  • 59
  • 90
0

var date1 = new Date(2010, 6, 17); var date2 = new Date(2013, 12, 18);

var diff = new Date(date2.getTime() - date1.getTime());

// diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)

console.log(diff.getUTCDate() - 1); // Gives day count of difference // 4

richessler
  • 84
  • 6
0

This will work for you.

function days(begin, end){
  var diff = new Date(end) - new Date(begin);
  return diff / 1000 / 60 / 60 / 24
}

If you want to do a lot more date manipulation Moment.js might be a good library for you.

> days('2015/11/30','2015/12/2')
2
> days('2015/11/30','2015/12/3')
3
> days('2015/11/30','2016/12/3')
369
Schechter
  • 224
  • 2
  • 5
0

You can use moment.js to perform any operation on dates.

To get number of days between 2 days:

var startDate = moment("12-25-2014", "MM-DD-YYYY");
var endDate = moment("10-18-2015", "MM-DD-YYYY");

var diffInDays = endDate.diff(startDate, 'days') // 297
Kunal Kapadia
  • 3,223
  • 2
  • 28
  • 36
0

I have noticed simple solution for this ,

var btdate = new Date('2015/11/30');
var etdate = new Date('2015/12/02');

var diff2 = etdate - btdate; //here diffrence in milliseconds

//lets convert milliseconds into days.
diff2 /= 1000; //to seconds
diff2 /= 60;  //to minutes
diff2 /= 60;  //to hours
diff2 /= 24;  //to days
console.log(diff2);
Azad
  • 5,144
  • 4
  • 28
  • 56