Skip to content

Instantly share code, notes, and snippets.

@menixator
Created July 21, 2016 19:15
Show Gist options
  • Save menixator/b6574f15541e49c2dcbdda0b55d59ff6 to your computer and use it in GitHub Desktop.
Save menixator/b6574f15541e49c2dcbdda0b55d59ff6 to your computer and use it in GitHub Desktop.
A tiny utility to convert milliseconds into a human readable format.
// Constants.
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
// Specify the minimum a unit can be before
// `ms()` adds it to the output.
var minimums = {
'second': 10,
'millisecond': 1000
}
var units = ['year', 'day', 'hour', 'minute', 'second', 'millisecond'];
// The concept the function runs with is,
// to floor the amount the provided milliseconds
// divided by the number of milliseconds that represent
// the respective unit, then pass on to the next unit -
// the remainder.
var ms = function(ms){
var map = [];
if (ms >= y){
map.push(Math.floor(ms/y))
ms = ms% y
} else {
map.push(0)
}
if (ms >= d){
map.push(Math.floor(ms/d))
ms = ms%d
} else {
map.push(0)
}
if (ms >= h){
map.push(Math.floor(ms/h))
ms = ms%h
} else {
map.push(0)
}
if (ms >= m){
map.push(Math.floor(ms/m))
ms = ms%m
} else {
map.push(0)
}
if (ms >= s){
map.push(Math.floor(ms/s))
ms = ms%s
} else {
map.push(0)
}
map.push(ms);
var filtered = map.map(function(value, i){
var key = units[i];
// If the value is `0` or if the value is less than the minimun it's discarded.
if (value === 0 || ({}.hasOwnProperty.call(minimums, key) && value < minimums[key])){
return null;
}
// Handle pluralizations.
if (value > 1){
key += 's'
}
return value + ' ' + key
}).filter(function(v){return v !== null});
// Join with an and if the length of the filtered
// elements is 2 or less.
if (filtered.length <= 2){
return filtered.join(' and ')
}
// Join with commas and an and if it's more than 2.
var last = filtered.pop();
return filtered.join(', ') + ' and ' + last
};
// Expositions.
ms.SECOND = s;
ms.MINUTE = m;
ms.HOUR = h;
ms.DAY = d;
ms.YEAR = y;
ms.minimums = minimums;
ms.units = units;
module.exports = ms;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment