From 443beda74190b5af3083625116e9a9fdd4aa0fe0 Mon Sep 17 00:00:00 2001 From: Eric Bailey Date: Tue, 18 Jun 2024 10:55:02 -0500 Subject: Add `useGetTimeAgo` and utils (#4556) * Create a testable version of ago() and re-enable the disabled test (#4364) * Enable the test of ago() * Use test cases This puts the input and the expected values next to each other. * Create dateDiff function This is a copy of ago(), but with the ability to specify the second date instead of using Date.now(). * Let ago() use dateDiff() * Move constants close to usage * Test dateDiff instead of ago This makes it possible to test the dates without being forced to rely on what the current date is. The commented out tests do not yet pass. This is fixed in later commits. * Update dateDiff and enable the remaining tests * Split up tests, use date-fns as helpers * Remove old test * Add long format * Add hook * Migrate to hooks * Delete old code * Or equal to * Update comment --------- Co-authored-by: Jan Aagaard --- src/lib/strings/time.ts | 42 ------------------------------------------ 1 file changed, 42 deletions(-) (limited to 'src/lib/strings/time.ts') diff --git a/src/lib/strings/time.ts b/src/lib/strings/time.ts index 8de4b52ae..1194e0240 100644 --- a/src/lib/strings/time.ts +++ b/src/lib/strings/time.ts @@ -1,45 +1,3 @@ -const NOW = 5 -const MINUTE = 60 -const HOUR = MINUTE * 60 -const DAY = HOUR * 24 -const MONTH_30 = DAY * 30 -const MONTH = DAY * 30.41675 // This results in 365.001 days in a year, which is close enough for nearly all cases -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 < NOW) { - return `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_30) { - return `${Math.round(diffSeconds / DAY)}d` - } else { - let months = diffSeconds / MONTH - if (months % 1 >= 0.9) { - months = Math.ceil(months) - } else { - months = Math.floor(months) - } - - if (months < 12) { - return `${months}mo` - } else { - return new Date(ts).toLocaleDateString() - } - } -} - export function niceDate(date: number | string | Date) { const d = new Date(date) return `${d.toLocaleDateString('en-us', { -- cgit 1.4.1