This post will discuss how to find the difference between two dates in days with JavaScript.

1. Using Date object

We can use the Date object and its getTime() function, which returns the number of milliseconds since January 1, 1970 00:00:00 UTC. We can create two Date objects with the dates we want to compare, and then subtract their getTime() values to get the difference in milliseconds. We can then convert the difference to days, hours, minutes, seconds, etc. by dividing it by the appropriate factors.

Download  Run Code

 
We may also use the - operator with Date objects, which returns the time difference in milliseconds between two Date objects. The following code illustrates this:

Download  Run Code

2. Using Moment.js library

The Moment.js is a popular lightweight library that simplifies working with dates and times in JavaScript. The moment() function returns a moment object that wraps a Date object and provides many useful functions and properties. We can use the diff() function to get the difference between two moment objects in various units, such as days, hours, minutes, seconds, etc. To get the difference in days, we can pass 'days' as the second argument, as demonstrated below:

Download Code

That’s all about finding the difference between the two dates in days in JavaScript.