Get difference between 2 dates in JavaScript
Question:
How to get the difference between 2 dates in JavaScript? Answer:
let startDate = new Date('2020-10-07');
let endDate = new Date('2020-11-12');
const DAY_IN_MS = 24 * 60 * 60 * 1000;
let timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
let dayDiff = Math.ceil(timeDiff / DAY_IN_MS);
console.log('Difference is: ' + dayDiff + ' days');
Description:
The getTime()
method returns the number of milliseconds since the Unix Epoch.
Note: JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds.
getTime()
always uses UTC for time representation. For example, a client browser in one timezone, getTime()
will be the same as a client browser in any other timezone.
You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.
Reference:
getTime() manual
Share "How to get the difference between 2 dates in JavaScript?"
Related snippets:
Tags:
javascript, date, difference, gettime Technical term:
Get difference between 2 dates in JavaScript