Write a function that takes two valid dates as an input and returns the difference between them in the number of days.
Example
Input: '10/15/2020' // mm/dd/yyyy '12/1/2020' // mm/dd/yyyy Output: 47
The good thing about working with JavaScript dates is that we can simply subtract two dates and will get the time difference in milliseconds.
We can then convert this millisecond to get the number of days, weeks, months.
In a day we have around 86400000
milliseconds.
const DAY_IN_MILLISECONDS = 1000 * 60 * 60 * 24; //1000 * seconds * minutes * hours
Thus we can divide the difference by this number and we will get our number of days.
const getDaysBetweenDates = (dateText1, dateText2) => { //millseconds in a day const DAY_IN_MILLISECONDS = 1000 * 60 * 60 * 24; //convert the date strings to actual dates const date1 = new Date(dateText1); const date2 = new Date(dateText2); // get the difference between the two days const diffTime = Math.abs(date2 - date1); // divide it by no of milliseconds in a single day const diffDays = Math.ceil(diffTime / DAY_IN_MILLISECONDS); //return the days return diffDays; }
Input: //1. mm/dd/yyyy 2.mm/dd/yyyy console.log(getDaysBetweenDates('10/15/2020', '12/1/2020')); //1. yyyy-mm-dd 2.mm/dd/yyyy console.log(getDaysBetweenDates('2022-01-30', '12/1/2020')); Output: 47 426