From da18658a5fb5b1f4f2c9af85b27c6d098affa296 Mon Sep 17 00:00:00 2001 From: Justin Edmund Date: Sat, 26 Feb 2022 17:45:37 -0800 Subject: [PATCH] Add timeAgo util function --- utils/timeAgo.tsx | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 utils/timeAgo.tsx diff --git a/utils/timeAgo.tsx b/utils/timeAgo.tsx new file mode 100644 index 00000000..3c510a71 --- /dev/null +++ b/utils/timeAgo.tsx @@ -0,0 +1,26 @@ + +const DIVISIONS = [ + { amount: 60, name: 'seconds' }, + { amount: 60, name: 'minutes' }, + { amount: 24, name: 'hours' }, + { amount: 7, name: 'days' }, + { amount: 4.34524, name: 'weeks' }, + { amount: 12, name: 'months' }, + { amount: Number.POSITIVE_INFINITY, name: 'years' } +] + +export function formatTimeAgo(date: Date, locale: string = 'en-us') { + const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }) + + let duration = (date.getTime() - new Date().getTime()) / 1000 + + for (let i = 0; i <= DIVISIONS.length; i++) { + const division = DIVISIONS[i] + + if (Math.abs(duration) < division.amount) { + return formatter.format(Math.round(duration), division.name) + } + + duration /= division.amount + } + } \ No newline at end of file