Created
January 12, 2022 13:26
-
-
Save A-D-E-A/fc3a3e8670da55949e4e8f5e310229cb to your computer and use it in GitHub Desktop.
Convert milliseconds to a formatted duration string [Javascript].
This file contains hidden or 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
/** | |
* Creates a duration string from a number of milliseconds. | |
* | |
* Example: | |
* ```js | |
* const dateA = new Date("2022-01-01T12:55:02"); | |
* const dateB = new Date("2022-01-08T15:00:00"); | |
* const msDuration = nowDate - someOlderDate; | |
* const str = msToDuration(msDuration); | |
* console.log(str); // "7 d 02 h 04 m 58 s" | |
* const otherStr = msToDuration(3000); | |
* console.log(otherStr); // "03 s" | |
* ``` | |
* | |
* @param ms Number of milliseconds | |
* @returns Formatted date string | |
*/ | |
function msToDuration(ms) { | |
// Returns an array with the integer division and modulo of (a,b). | |
// Used bellow for readability when computing days/hours/etc. | |
const divMod = (a, b) => [Math.floor(a / b), a % b]; | |
// Get the days, hours, minutes and seconds as integers. | |
const [days, ms1] = divMod(ms, 24 * 60 * 60 * 1000); | |
const [hours, ms2] = divMod(ms1, 60 * 60 * 1000); | |
const [minutes, ms3] = divMod(ms2, 60 * 1000); | |
const [seconds, _] = divMod(ms3, 1000); | |
// Boolean checks (if false then don't display them). | |
const hasDays = days > 0; | |
const hasHours = hours > 0 || hasDays; | |
const hasMinutes = minutes > 0 || hasHours; | |
const hasSeconds = seconds > 0 || hasMinutes; | |
// Construction of the formatted string. | |
const str = | |
(hasDays ? `${days} d ` : "") + | |
(hasHours ? `${hours.toString().padStart(2, "0")} h ` : "") + | |
(hasMinutes ? `${minutes.toString().padStart(2, "0")} m ` : "") + | |
(hasSeconds ? `${seconds.toString().padStart(2, "0")} s` : ""); | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment