calculate hours between two dates in javascript

To calculate the difference in hours between two dates in JavaScript, you can subtract the two dates and then divide the result by the number of milliseconds in an hour.

Here's an example of how you can do this:

index.tsx
function getHoursBetweenDates(startDate, endDate) {
  // Calculate the difference in milliseconds between the two dates
  const differenceInMilliseconds = endDate - startDate;
  
  // Calculate the difference in hours by dividing the milliseconds by the number of milliseconds in an hour
  const differenceInHours = differenceInMilliseconds / (1000 * 60 * 60);
  
  // Return the difference in hours
  return differenceInHours;
}

// Usage example:
const startDate = new Date('2021-01-01 08:00');
const endDate = new Date('2021-01-01 13:30');

const hoursDifference = getHoursBetweenDates(startDate, endDate);
console.log(hoursDifference);
640 chars
18 lines

This will output 5.5, indicating that there are 5.5 hours between the two dates.

related categories

gistlibby LogSnag