Last active
April 16, 2020 14:02
-
-
Save robpataki/d0b40a1cbbb71764dd94e16cbc99d42f to your computer and use it in GitHub Desktop.
Convert time in milliseconds to human readable hours:minutes:seconds formatedt string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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}`;
}
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
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:
output: 3660000 millis == 01hr 01m 00s
output: 3600000 millis == 01hr 00m 00s
output: 3599000 millis == 00h 59m 59s