turn seconds to number of days, hour, minutes in javascript

index.tsx
function formatTime(totalSeconds) {
  const days = Math.floor(totalSeconds / 86400);
  const hours = Math.floor((totalSeconds % 86400) / 3600);
  const minutes = Math.floor(((totalSeconds % 86400) % 3600) / 60);
  const seconds = Math.floor(totalSeconds % 60);
  
  const result = (days > 0 ? days + ' day' + (days > 1 ? 's ' : ' ') : '') +
    (hours > 0 ? hours + ' hour' + (hours > 1 ? 's ' : ' ') : '') +
    (minutes > 0 ? minutes + ' minute' + (minutes > 1 ? 's ' : ' ') : '') +
    (seconds > 0 ? seconds + ' second' + (seconds > 1 ? 's' : '') : '');
  
  return result.trim();
}

console.log(formatTime(120));  // "2 minutes"
console.log(formatTime(3600)); // "1 hour"
console.log(formatTime(86400)); // "1 day"
console.log(formatTime(90061)); // "1 day 1 hour 1 minute 1 second"
788 chars
19 lines

We can define a function named formatTime that takes the total time in seconds as a parameter. The function calculates the days, hours, minutes, and seconds from the given total seconds. Finally, it returns the formatted time as a string.

We are using the Math.floor() function to convert the decimal values into integers. We are also using the modulo operator to calculate the remaining seconds, after the days and hours have been calculated.

Lastly, the formatted time string is built using conditional statements that check whether the days, hours, minutes and seconds are greater than 1 or not. This allows us to pluralize the units of time correctly in the output string.

gistlibby LogSnag