Last active
February 13, 2024 01:09
-
-
Save steve8708/ada9bff2600228789fce2fcc95427e39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const minute = 60; | |
const hour = minute * 60; | |
const day = hour * 24; | |
const week = day * 7; | |
const month = day * 30; | |
const year = day * 365; | |
/** | |
* Convert a date to a relative time string, such as | |
* "a minute ago", "in 2 hours", "yesterday", "3 months ago", etc. | |
*/ | |
export function getRelativeTimeString( | |
date: Date | number, | |
lang = navigator.language | |
): string { | |
const time = date instanceof Date ? date.getTime() : date; | |
const delta = Math.round((time - Date.now()) / 1000); | |
const absoluteDelta = Math.abs(delta); | |
const times: [number, Intl.RelativeTimeFormatUnit, number][] = [ | |
[minute, "second", 1], | |
[hour, "minute", minute], | |
[day, "hour", hour], | |
[week, "day", day], | |
[month, "week", week], | |
[year, "month", month], | |
[Infinity, "year", year], | |
]; | |
let divider = year; | |
let timeType: Intl.RelativeTimeFormatUnit = "year"; | |
for (const [num, timeInterval, div] of times) { | |
if (absoluteDelta < num) { | |
divider = div; | |
timeType = timeInterval; | |
break; | |
} | |
} | |
const rtf = new Intl.RelativeTimeFormat(lang, { | |
numeric: "auto", | |
}); | |
return rtf.format(Math.floor(delta / divider), timeType); | |
} |
@LewisJEllis i love it!
I noticed a bug, when doing getRelativeTimeString(1632734100000)
which is Mon Sep 27 2021 09:15:00 GMT+0000
, I get 6 years ago rather than 6 months ago
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can tighten it up a little further :)
108 line function body with no predefined constants, all behavior preserved: https://gist.github.com/LewisJEllis/9ad1f35d102de8eee78f6bd081d486ad