Find the number of days between two dates in Javascript

Learn to find the difference between two dates in javascript.

Let’s take an example of what we are going to do. We have a function that takes two dates as the input, and it returns the number of days.

If we pass May 22, 2019 and May 28, 2019, then it returns 7.

The solution to the problems

1. Convert the date object in to millisecond
2. Subtract the second date from first date.
3. Divide that by number of milliseconds per day (86400000) calculated by (1000 * 60 * 60 * 24)
1000 --> 1 second
60   --> 60 minutes
60  -->  60 seconds
24  --> 24 hours

Program

const MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24;
function dayDifference(date1, date2) {  
   var timeDiff = Math.abs(date2.getTime() - date1.getTime());
   var diffDays = Math.ceil(timeDiff / MILLISECONDS_PER_DAY);
   return diffDays;
}
var date1 = new Date(); //May 28 2019 
var date2 = new Date(); 
date2.setDate(22);
dayDifference(date, date1); // 7

Note: dateObj.getTime() β†’ convert date to milliseconds.

Follow Javascript JeepπŸš™ for more interesting posts.


https://gitconnected.com/learn/javascript

Leave a comment

Design a site like this with WordPress.com
Get started