How to use UTC timestamps In Javascript
Another method to calculate the number of days between two dates involves converting both dates into UTC timestamps and then finding the difference. This approach can be useful when dealing with dates across different time zones, ensuring consistent results regardless of the local time zone settings.
Example:
let date1 = new Date("01/16/2024");
let date2 = new Date("01/26/2024");
// Convert dates to UTC timestamps
let utc1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
let utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
// Calculate the time difference in milliseconds
let timeDiff = Math.abs(utc2 - utc1);
// Convert milliseconds to days
let daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
// Display the result
console.log(`Total number of days between dates:
${date1.toDateString()} and ${date2.toDateString()} is: ${daysDiff} days`);
Output
Total number of days between dates: Tue Jan 16 2024 and Fri Jan 26 2024 is: 10 days
How to calculate the number of days between two dates in JavaScript ?
To calculate the number of days between two dates in JavaScript, we use the Date object and perform simple arithmetic using milliseconds. Below are the methods commonly used to determine the number of days between two dates:
Table of Content
- Using Two different dates
- Using One fixed date
- Using UTC timestamps
- Using Intl.DateTimeFormat Method