Skip to content

Instantly share code, notes, and snippets.

@stefanmaric
Last active September 21, 2021 22:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanmaric/84ca8f69dc644ae3fd498d49f9036e01 to your computer and use it in GitHub Desktop.
Save stefanmaric/84ca8f69dc644ae3fd498d49f9036e01 to your computer and use it in GitHub Desktop.
Util function to select unit and value for the Intl.RelativeTimeFormat API
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
@loganvolkers
Copy link

Thanks! Much better than having to fork DayJS' implementation

@loganvolkers
Copy link

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