Created
May 16, 2022 19:58
-
-
Save codergautam/1fa807ca9a61cb3b6da90b7c1b83c20e to your computer and use it in GitHub Desktop.
Millisecond to Human Readable time converter
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
function msToTime(duration) { | |
const portions = []; | |
const msInDay = 1000 * 60 * 60 * 24; | |
const days = Math.trunc(duration / msInDay); | |
if (days > 0) { | |
portions.push(days + 'd'); | |
duration = duration - (days * msInDay); | |
} | |
const msInHour = 1000 * 60 * 60; | |
const hours = Math.trunc(duration / msInHour); | |
if (hours > 0) { | |
portions.push(hours + 'h'); | |
duration = duration - (hours * msInHour); | |
} | |
const msInMinute = 1000 * 60; | |
const minutes = Math.trunc(duration / msInMinute); | |
if (minutes > 0) { | |
portions.push(minutes + 'm'); | |
duration = duration - (minutes * msInMinute); | |
} | |
const seconds = Math.trunc(duration / 1000); | |
if (seconds > 0) { | |
portions.push(seconds + 's'); | |
} | |
return portions.join(' '); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want a shorter string, just do
return portions[0]