40

I need to get the difference between two dates in days.

Up to now, I've been able to get the difference between two dates, but not in days:

date1.getTime() - date2.getTime();

Any ideas?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • 3
    I strongly believe this question is not duplicate to attached. The attached question/answer gives different between two dates in years/months/days, but this question is different between two dates in days only. The below answer by @mohammad works. – yallam Aug 12 '17 at 05:03
  • The date-fns library's differenceInDays function is good for this https://date-fns.org/docs/differenceInDays – Ollie Aug 30 '20 at 22:55

2 Answers2

78
var date1 = new Date(2023, 1, 1);
var date2 = new Date(2023, 2, 1);
var diff = Math.abs(date1.getTime() - date2.getTime());
var diffDays = Math.ceil(diff / (1000 * 3600 * 24)); 
console.log("Diff in Days: " + diffDays);
Master
  • 2,945
  • 5
  • 34
  • 65
mohammad
  • 2,232
  • 1
  • 18
  • 38
16

I believe the shortest route is:

var diff = date1.valueOf() - date2.valueOf();
Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
  • 2
    I am not sure that is entirely correct by itself, I think you still need to do the diffDays calculation from the other answer. But it is correct you can replace the first statement in the other answer with what you suggest. – aggaton Apr 16 '20 at 19:23