Last active
September 21, 2021 22:20
-
-
Save stefanmaric/84ca8f69dc644ae3fd498d49f9036e01 to your computer and use it in GitHub Desktop.
Util function to select unit and value for the Intl.RelativeTimeFormat API
This file contains hidden or 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
export const UNITS = [ | |
{ | |
multiplier: 1000, | |
name: 'second', | |
threshold: 45, | |
}, | |
{ | |
multiplier: 60, | |
name: 'minute', | |
threshold: 45, | |
}, | |
{ | |
multiplier: 60, | |
name: 'hour', | |
threshold: 22, | |
}, | |
{ | |
multiplier: 24, | |
name: 'day', | |
threshold: 5, | |
}, | |
{ | |
multiplier: 7, | |
name: 'week', | |
threshold: 4, | |
}, | |
{ | |
multiplier: 30, | |
name: 'month', | |
threshold: 4, | |
}, | |
{ | |
multiplier: 30, | |
name: 'quarter', | |
threshold: 4, | |
}, | |
{ | |
multiplier: 4, | |
name: 'year', | |
threshold: null, | |
}, | |
] | |
const selectRelativeTimeUnit = (to, from = Date.now(), config = {}) => { | |
const { thresholds = {} } = config | |
let diff = to - from | |
let value = diff | |
let unit = 'milliseconds' | |
for (let u of UNITS) { | |
const threshold = u.name in thresholds ? thresholds[u.name] : u.threshold | |
value = value / u.multiplier | |
unit = u.name | |
if (typeof threshold !== 'number' || Math.abs(value) < threshold) { | |
break | |
} | |
} | |
if (Math.abs(value) < 1) { | |
value = value > 0 ? 1 : -1 | |
} else { | |
value = Math.round(value) | |
} | |
return { | |
unit, | |
value, | |
} | |
} | |
export default selectRelativeTimeUnit |
Similar library (for others on the internet finding this gist): https://www.npmjs.com/package/@formatjs/intl-utils
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! Much better than having to fork DayJS' implementation