UNPKG

1.24 kBJavaScriptView Raw
1/**
2 * Utility module to work with time.
3 *
4 * @module time
5 */
6
7import * as metric from './metric.js'
8import * as math from './math.js'
9
10/**
11 * Return current time.
12 *
13 * @return {Date}
14 */
15export const getDate = () => new Date()
16
17/**
18 * Return current unix time.
19 *
20 * @return {number}
21 */
22export const getUnixTime = Date.now
23
24/**
25 * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.
26 *
27 * @param {number} d duration in milliseconds
28 * @return {string} humanized approximation of time
29 */
30export const humanizeDuration = d => {
31 if (d < 60000) {
32 const p = metric.prefix(d, -1)
33 return math.round(p.n * 100) / 100 + p.prefix + 's'
34 }
35 d = math.floor(d / 1000)
36 const seconds = d % 60
37 const minutes = math.floor(d / 60) % 60
38 const hours = math.floor(d / 3600) % 24
39 const days = math.floor(d / 86400)
40 if (days > 0) {
41 return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')
42 }
43 if (hours > 0) {
44 /* istanbul ignore next */
45 return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')
46 }
47 return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')
48}