about summary refs log tree commit diff
path: root/src/lib/strings/time.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/strings/time.ts')
-rw-r--r--src/lib/strings/time.ts29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/lib/strings/time.ts b/src/lib/strings/time.ts
new file mode 100644
index 000000000..4f62eeba9
--- /dev/null
+++ b/src/lib/strings/time.ts
@@ -0,0 +1,29 @@
+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 < 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()
+  }
+}