scoresaber-reloadedv3/src/common/time-utils.ts

27 lines
791 B
TypeScript
Raw Normal View History

2024-09-11 19:10:27 +00:00
/**
* This function returns the time ago of the input date
*
* @param input Date | number
* @returns the format of the time ago
*/
export function timeAgo(input: Date | number) {
const date = input instanceof Date ? input : new Date(input);
const formatter = new Intl.RelativeTimeFormat("en");
const ranges: { [key: string]: number } = {
2024-09-11 19:15:05 +00:00
year: 3600 * 24 * 365,
month: 3600 * 24 * 30,
week: 3600 * 24 * 7,
day: 3600 * 24,
hour: 3600,
minute: 60,
second: 1,
2024-09-11 19:10:27 +00:00
};
const secondsElapsed = (date.getTime() - Date.now()) / 1000;
2024-09-11 19:16:33 +00:00
for (const key in ranges) {
2024-09-11 19:10:27 +00:00
if (ranges[key] < Math.abs(secondsElapsed)) {
const delta = secondsElapsed / ranges[key];
2024-09-11 19:15:05 +00:00
return formatter.format(Math.round(delta), key as Intl.RelativeTimeFormatUnit);
2024-09-11 19:10:27 +00:00
}
}
}