How to calculate the difference in hours between two dates in JavaScript?

To calculate the difference in hours between two dates in JavaScript, you can use the getTime() method to convert the dates to timestamp values, subtract the timestamps, and then divide by the number of milliseconds in an hour. Here's an example:

const date1 = new Date('2023-06-01 12:00:00'); // first date const date2 = new Date('2023-06-01 18:30:00'); // second date const timestamp1 = date1.getTime(); // get timestamp for date1 const timestamp2 = date2.getTime(); // get timestamp for date2 const hourDifference = (timestamp2 - timestamp1) / (1000 * 60 * 60); // calculate the difference in hours console.log(hourDifference); // Output: 6.5 hours

In this example, getTime() is used to get the timestamp for each date, which represents the number of milliseconds since January 1, 1970. The difference between the two timestamps is then divided by the number of milliseconds in an hour (1000 * 60 * 60) to get the difference in hours.