To calculate the difference in days between two dates in JavaScript, you can create two Date objects representing the dates and then calculate the difference in milliseconds between them. Then, convert the difference to days by dividing it by the number of milliseconds in a day (24 * 60 * 60 * 1000). Here's an example:
function getDaysDifference(date1, date2) {
const oneDay = 24 * 60 * 60 * 1000; // milliseconds in a day
const firstDate = new Date(date1);
const secondDate = new Date(date2);
const difference = Math.round(Math.abs((firstDate - secondDate) / oneDay));
return difference;
}
// Example usage:
const date1 = '2022-01-01';
const date2 = '2022-12-31';
const differenceInDays = getDaysDifference(date1, date2);
console.log(differenceInDays); // Output: 364
In this example, we define a function getDaysDifference
that accepts two date strings as parameters. Inside the function, we create two Date objects from the input strings. We then calculate the absolute difference in milliseconds between the two dates using the formula (firstDate - secondDate) / oneDay
. Finally, we round the difference using Math.round
and return it as the result.