Find difference between two dates in JavaScript
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Two date strings const first = '01/25/2020'; const second = 'January 15, 2020'; // Create two Date objects with the dates to compare const x = new Date(first); const y = new Date(second); // Get the difference in milliseconds const diff = x.getTime() - y.getTime(); // seconds = milliseconds / 1000 // minutes = seconds / 60 // hours = minutes / 60 // Days = hours / 24 // Convert the difference to days const days = diff / (1000 * 60 * 60 * 24); // Print the result console.log(days + " days"); // 10 days |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Two date strings const first = '01/25/2020'; const second = 'January 15, 2020'; // Create two Date objects with the dates to compare const x = new Date(first); const y = new Date(second); // Get the difference in milliseconds const diff = x - y; // Convert the difference to days const days = diff / (1000 * 60 * 60 * 24); // Print the result console.log(days + " days"); // 10 days |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Import Moment library const moment = require('moment'); // Two date strings const first = '01/25/2020'; const second = 'January 15, 2020'; // Create two moment objects with the dates to compare const x = new moment(first, 'L'); const y = new moment(second, 'LL') // Get the difference in days const days = x.diff(y, 'days'); // Print the result console.log(days + " days"); // 10 days |
That’s all about finding the difference between the two dates in days in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)