0

Date difference is not working properly. The difference of dates 2018/10/22 & 2018/10/28 is 6 this result is correct. But difference of dates 2018/10/22 & 2018/10/29 is 8 this result is wrong. Any help would be appreciated.

var date1 = new Date("2018/10/22");
var date2 = new Date("2018/10/28");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);

Result is 6

var date1 = new Date("2018/10/22");
var date2 = new Date("2018/10/29");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);

Result is 8

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Sarath TS
  • 2,432
  • 6
  • 32
  • 79
  • `"2018/10/28"` isn't a format the `Date` constructor knows how to parse, reliably. – T.J. Crowder Oct 10 '18 at 07:11
  • I don't think this is a dup, as it's actually a European Summer Time issue. – Ken Y-N Oct 10 '18 at 07:12
  • @T.J.Crowder your right i misread it and just commented, saw month before date – Karan Shishoo Oct 10 '18 at 07:13
  • Also i just tested this in my chrome console im getting the difference as 6 and 7 maybe its not an issue with the code ? – Karan Shishoo Oct 10 '18 at 07:15
  • Duplicate of [*How do I get the number of days between two dates in JavaScript?*](https://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript?s=1|237.3465) and [several others](/search?q=%5Bjs%5D+days+between+dates). – T.J. Crowder Oct 10 '18 at 07:15
  • @casualcoder My computer time is german time. Javascript date format is year month date. – Sarath TS Oct 10 '18 at 07:18

1 Answers1

2

@ken-y-n is right this is a Europen Summer Time issue.

In the morning of 28.10.2018 at 3:00 am the time is reset to 2:00 am. So that day is longer (90000000 ms instead of 86400000). That leads to

timeDiff / (1000 * 3600 * 24) == 7.041666666666667

instead of 7. Which Math.ceil brings up to 8...

To Fix this you can follow the advice given in the answer referred to by @t-j-crowder in the comments... (TimeDiff in Javascript)).

In short: round the timediff to the nearest whole integer to adjust for Daylight Saving time:

var date1 = new Date("2018/10/22");
var date2 = new Date("2018/10/29");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(Math.round(timeDiff / (1000 * 3600 * 24)));
console.log(diffDays);

For more details you can follow the link to the answer by @miles

dertoni
  • 1,763
  • 2
  • 24
  • 47