Skip to content

Instantly share code, notes, and snippets.

@robpataki
Last active April 16, 2020 14:02
Show Gist options
  • Save robpataki/d0b40a1cbbb71764dd94e16cbc99d42f to your computer and use it in GitHub Desktop.
Save robpataki/d0b40a1cbbb71764dd94e16cbc99d42f to your computer and use it in GitHub Desktop.
Convert time in milliseconds to human readable hours:minutes:seconds formatedt string
var getTimeString = function(timeInMs) {
var delim = ":";
var hours = Math.ceil(timeInMs / (1000 * 60 * 60) % 60);
var minutes = Math.floor(timeInMs / (1000 * 60) % 60);
var seconds = Math.floor(timeInMs / 1000 % 60);
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
return hours + delim + minutes + delim + seconds;
}
@mishelen
Copy link

More robust ?!

function convertToString(ms, delim = " : ") {
  const showWith0 = value => (value < 10 ? `0${value}` : value);
  const hours = showWith0(Math.floor((ms / (1000 * 60 * 60)) % 60));
  const minutes = showWith0(Math.floor((ms / (1000 * 60)) % 60));
  const seconds = showWith0(Math.floor((ms / 1000) % 60));
  return `${parseInt(hours) ? `${hours}${delim}` : ""}${minutes}${delim}${seconds}`;
}

@MichelGratton
Copy link

MichelGratton commented Apr 16, 2020

Here is my version of it with support for negative values.

getTimeString = (ms, sep = ':') => {
  const sign = ~~ms < 0 ? '-' : '';
  const absMs = Math.abs(~~ms);
  const [h, m, s] = [1000 * 60 * 60, 1000 * 60, 1000].map(calcMs => ('0' + ~~((absMs / calcMs) % 60)).substr(-2));
  return `${sign}${parseInt(h, 10) ? `${h}${sep}` : ''}${m}${sep}${s}`;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment