UNPKG

@enspirit/emb

Version:

A replacement for our Makefile-for-monorepos

27 lines (26 loc) 885 B
const DATE_UNITS = { day: 86_400, hour: 3600, minute: 60, second: 1, }; const getSecondsDiff = (timestamp) => (Date.now() - timestamp) / 1000; const getUnitAndValueDate = (secondsElapsed) => { for (const [unit, secondsInUnit] of Object.entries(DATE_UNITS)) { if (secondsElapsed >= secondsInUnit || unit === 'second') { const value = Math.floor(secondsElapsed / secondsInUnit) * -1; return { value, unit: unit }; } } const value = Math.floor(secondsElapsed / DATE_UNITS.day) * -1; return { value, unit: 'day' }; }; export const getTimeAgo = (timestamp) => { if (!timestamp) { return; } const rtf = new Intl.RelativeTimeFormat(); const secondsElapsed = getSecondsDiff(timestamp * 1000); const { value, unit } = getUnitAndValueDate(secondsElapsed); return rtf.format(value, unit); };