create a function called calculatehours javascript in javascript

Here is an example of how to create a function called "calculateHours" in JavaScript that calculates the number of hours between two given times:

index.tsx
function calculateHours(startTime, endTime) {
  const start = new Date(`2021-01-01T${startTime}:00`);
  const end = new Date(`2021-01-01T${endTime}:00`);
  
  const duration = end - start;
  const hours = duration / 1000 / 60 / 60;
  
  return hours.toFixed(2);
}

// Example usage:
const hours = calculateHours("09:00", "17:30");
console.log(hours); // Output: 8.50
367 chars
14 lines

This function takes two strings as arguments, representing the start and end times in the format HH:mm, and returns the number of hours as a string with two decimal places. It uses the Date constructor to create Date objects for each time, calculates the duration between them in milliseconds, divides by 1000 * 60 * 60 to convert to hours, and then uses the toFixed method to format the output.

gistlibby LogSnag