Skip to content

Instantly share code, notes, and snippets.

@steve8708
Last active February 13, 2024 01:09
Show Gist options
  • Save steve8708/ada9bff2600228789fce2fcc95427e39 to your computer and use it in GitHub Desktop.
Save steve8708/ada9bff2600228789fce2fcc95427e39 to your computer and use it in GitHub Desktop.
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);
}
@steve8708
Copy link
Author

@LewisJEllis i love it!

@pavsidhu
Copy link

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