@onesy/date
Version:
Time and date utils library
53 lines (48 loc) • 1.93 kB
JavaScript
import is from '@onesy/utils/is';
import clamp from '@onesy/utils/clamp';
export default function duration(value) {
let unitAbbr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
let raw = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
let separator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ' ';
let display = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
let options = arguments.length > 5 ? arguments[5] : undefined;
const l = (options === null || options === void 0 ? void 0 : options.l) || (value => value);
if (is('number', value)) {
let result = '';
let milliseconds = value;
const values = [];
const valuesRaw = {};
const millisecondsInTime = {
millisecond: 1,
second: 1e3,
minute: 60 * 1e3,
hour: 60 * 60 * 1e3,
day: 24 * 60 * 60 * 1e3,
month: 30 * 24 * 60 * 60 * 1e3,
year: 12 * 30 * 24 * 60 * 60 * 1e3
};
const unitsAbbr = {
millisecond: 'ms',
second: 's',
minute: 'm',
hour: 'h',
day: 'd',
month: 'mo',
year: 'y'
};
for (const unit of display) {
if (millisecondsInTime[unit]) {
const value_ = clamp(Math.floor(milliseconds / millisecondsInTime[unit]), 0);
if (value_ > 0) {
milliseconds -= value_ * millisecondsInTime[unit];
valuesRaw[unit] = value_;
let valueTime = value_;
if (unitAbbr) valueTime = "".concat(valueTime, " ").concat(l(unitsAbbr[unit]));else valueTime = "".concat(valueTime, " ").concat(l("".concat(unit).concat(value_ > 1 ? 's' : '')));
values.push(valueTime);
}
}
}
values.forEach(value_ => result += "".concat(separator).concat(value_));
return raw ? valuesRaw : result.trim();
}
}