about summary refs log tree commit diff
path: root/src/view/lib/strings.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/view/lib/strings.ts')
-rw-r--r--src/view/lib/strings.ts32
1 files changed, 32 insertions, 0 deletions
diff --git a/src/view/lib/strings.ts b/src/view/lib/strings.ts
index 3ef707dd8..30426e674 100644
--- a/src/view/lib/strings.ts
+++ b/src/view/lib/strings.ts
@@ -21,3 +21,35 @@ export function makeRecordUri(
   urip.recordKey = recordKey
   return urip.toString()
 }
+
+const MINUTE = 60
+const HOUR = MINUTE * 60
+const DAY = HOUR * 24
+const MONTH = DAY * 30
+const YEAR = DAY * 365
+export function ago(date: number | string | Date): string {
+  let ts: number
+  if (typeof date === 'string') {
+    ts = Number(new Date(date))
+  } else if (date instanceof Date) {
+    ts = Number(date)
+  } else {
+    ts = date
+  }
+  const diffSeconds = Math.floor((Date.now() - ts) / 1e3)
+  if (diffSeconds === 0) {
+    return 'just now'
+  } else if (diffSeconds < MINUTE) {
+    return `${diffSeconds}s`
+  } else if (diffSeconds < HOUR) {
+    return `${Math.floor(diffSeconds / MINUTE)}m`
+  } else if (diffSeconds < DAY) {
+    return `${Math.floor(diffSeconds / HOUR)}h`
+  } else if (diffSeconds < MONTH) {
+    return `${Math.floor(diffSeconds / DAY)}d`
+  } else if (diffSeconds < YEAR) {
+    return `${Math.floor(diffSeconds / MONTH)}mo`
+  } else {
+    return new Date(ts).toLocaleDateString()
+  }
+}