1 2 3 4
const date1 = new Date('2022-01-01'); const date2 = new Date('2022-02-01');
2. Calculate the difference between the two dates using the getTime() method to obtain the timestamps in milliseconds:
1 2 3
const timeDiff = date2.getTime() - date1.getTime();
3. Convert the time difference to the desired unit (e.g., days, hours, minutes) by dividing it by the appropriate conversion factor:
1 2 3 4 5
const daysDiff = timeDiff / (1000 * 60 * 60 * 24); // Convert milliseconds to days const hoursDiff = timeDiff / (1000 * 60 * 60); // Convert milliseconds to hours const minutesDiff = timeDiff / (1000 * 60); // Convert milliseconds to minutes
Adjust the conversion factor based on the desired unit of measurement.
Note: The calculated difference will be in milliseconds. You can further convert it to the desired time unit by dividing the time difference by the appropriate conversion factor.
For example, to calculate the difference in days, divide the time difference by
(1000 * 60 * 60 * 24), which represents the number of milliseconds in a day.
Make sure that both date objects are valid instances of the Date object. If you have date values in other formats (e.g., strings), you may need to parse them into Date objects using appropriate methods or libraries like Moment.js.