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;
}
@owl-93
Copy link

owl-93 commented Dec 15, 2017

I believe line 3 needs to be use Math.floor otherwise this will report 1 hour when minutes are less than 60. Here is my version of it in ES6:

static convertMillisToTime(millis){
        let delim = " ";
        let hours = Math.floor(millis / (1000 * 60 * 60) % 60);
        let minutes = Math.floor(millis / (1000 * 60) % 60);
        let seconds = Math.floor(millis / 1000 % 60);
        hours = hours < 10 ? '0' + hours : hours;
        minutes = minutes < 10 ? '0' + minutes : minutes;
        seconds = seconds < 10 ? '0' + seconds : seconds;
        return hours + 'h'+ delim + minutes + 'm' + delim + seconds + 's';
}

output: 3660000 millis == 01hr 01m 00s
output: 3600000 millis == 01hr 00m 00s
output: 3599000 millis == 00h 59m 59s

@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