Skip to content

Instantly share code, notes, and snippets.

@codergautam
Created May 16, 2022 19:58
Show Gist options
  • Save codergautam/1fa807ca9a61cb3b6da90b7c1b83c20e to your computer and use it in GitHub Desktop.
Save codergautam/1fa807ca9a61cb3b6da90b7c1b83c20e to your computer and use it in GitHub Desktop.
Millisecond to Human Readable time converter
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(' ');
}
@codergautam
Copy link
Author

If you want a shorter string, just do return portions[0]

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