0

I'm trying to count the days between 2 dates. It goes well if both dates are in the same month but not if they are in different. Here is an example where it returns the correct number(1 day):

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017,11,29);
var secondDate = new Date(2017,11,30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
console.log(diffDays);

Here is another example. In this case counting the days between last day of november and the 1st day of december, that should be 1 but returns 2

var oneDay = 24*60*60*1000; 
var firstDate = new Date(2017,11,30);
var secondDate = new Date(2017,12,1);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
console.log(diffDays);

I have observed that it returns wrong number if the months are different and if one or both months are conformed by less than 31 days, it adds the number of days missing from the month(s) that have less that 31, in this case 1 because november has 30 days and december 31, 1 + 1(missing days) = 2. Any Idea of how to get it right is very welcomed.

Cactux
  • 27
  • 7

3 Answers3

2

When creating a date with new Date(year, month, date), please be aware that the month argument is 0-based not 1-based. Read more on MDN: Date.

Therefore, in your second example, you are calculating the dates between 30 December 2017 and 1 January 2018, which is indeed 2 days rather than 1.

Richard Pickett
  • 482
  • 8
  • 17
2

Your problem right now isn't the way to get Days (Although due to leap seconds, days and confusing times, that's a problem that could happen, see: How do I get the number of days between two dates in JavaScript?).

Your problem is that you're expecting different behaviour out of the Date constructor.

The Date constructor is using 0 indexed months, as such

var firstDate = new Date(2017,11,30); // 30th of december of 2017
var secondDate = new Date(2017,12,1); // 1st of January of 2018
// Second date is the 1st of january because it rolls over.

new Date(2016,0,1) // the 1st of January of 2016.

refer to the 30th of december and the 1st of January of 2018, hence the answer says there's the 31th and the 1st between them, hence 2 days.

Imme
  • 151
  • 3
  • OOh I see.. Thanks a lot, I didn't knew that. – Cactux Nov 16 '17 at 19:23
  • Just curious why this answer was accepted over mine given I answered first (by just one minute) but the answers are essentially the same? In addition, I provided a link to the MDN documentation for the Date object. – Richard Pickett Nov 16 '17 at 23:38
-2

Your rounding function is likely what is causing the issue. Try Math.floor instead to round down, and this will likely solve your problem.

wilsonhobbs
  • 941
  • 8
  • 18