Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
Copy link

LewisJEllis commented Mar 17, 2022

can tighten it up a little further :)

10 8 line function body with no predefined constants, all behavior preserved: https://gist.github.com/LewisJEllis/9ad1f35d102de8eee78f6bd081d486ad

@steve8708
Copy link
Author

steve8708 commented Mar 17, 2022

@LewisJEllis i love it!

@pavsidhu
Copy link

pavsidhu commented Mar 24, 2022

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