ms to m:s in javascript

To convert minutes and seconds in the format mm:ss (e.g., 125 seconds = "02:05"), you can use the following JavaScript function:

index.tsx
function msToMinutesAndSeconds(ms) {
  let minutes = Math.floor(ms / 60000); // 1 minute = 60000 milliseconds
  let seconds = ((ms % 60000) / 1000).toFixed(0);
  return (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
}
252 chars
6 lines

Here's an example usage:

index.tsx
let durationInSeconds = 125;
let durationFormatted = msToMinutesAndSeconds(durationInSeconds * 1000);
console.log(durationFormatted); // Output: "02:05"
153 chars
4 lines

In the above code, we multiply durationInSeconds by 1000 to convert it to milliseconds before passing it to the function. The function then calculates the minutes and seconds and returns the formatted string. Note that the function assumes the input value is in milliseconds, so adjust accordingly if your input is in a different unit.

Also, keep in mind that this function assumes the input value is a positive duration. Handling negative durations (such as negative seconds) would require additional logic.

related categories

gistlibby LogSnag