This commit is contained in:
parent
1faa97b332
commit
bd4f49205b
@ -1,28 +1,41 @@
|
||||
/**
|
||||
* This function returns the time ago of the input date
|
||||
*
|
||||
* @param input Date | number
|
||||
* @param input Date | number (timestamp)
|
||||
* @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 } = {
|
||||
year: 3600 * 24 * 365,
|
||||
month: 3600 * 24 * 30,
|
||||
week: 3600 * 24 * 7,
|
||||
day: 3600 * 24,
|
||||
hour: 3600,
|
||||
minute: 60,
|
||||
second: 1,
|
||||
};
|
||||
const secondsElapsed = (date.getTime() - Date.now()) / 1000;
|
||||
for (const key in ranges) {
|
||||
if (ranges[key] < Math.abs(secondsElapsed)) {
|
||||
const delta = secondsElapsed / ranges[key];
|
||||
return formatter.format(Math.round(delta), key as Intl.RelativeTimeFormatUnit);
|
||||
}
|
||||
export function timeAgo(input: number) {
|
||||
const inputDate = new Date(input).getTime(); // Convert input to a Date object if it's not already
|
||||
const now = new Date().getTime();
|
||||
const deltaSeconds = Math.floor((now - inputDate) / 1000); // Get time difference in seconds
|
||||
|
||||
if (deltaSeconds < 60) {
|
||||
return "just now";
|
||||
}
|
||||
|
||||
const timeUnits = [
|
||||
{ unit: "y", seconds: 60 * 60 * 24 * 365 }, // years
|
||||
{ unit: "mo", seconds: 60 * 60 * 24 * 30 }, // months
|
||||
{ unit: "d", seconds: 60 * 60 * 24 }, // days
|
||||
{ unit: "h", seconds: 60 * 60 }, // hours
|
||||
{ unit: "m", seconds: 60 }, // minutes
|
||||
];
|
||||
|
||||
let result = [];
|
||||
let remainingSeconds = deltaSeconds;
|
||||
|
||||
for (let { unit, seconds } of timeUnits) {
|
||||
const count = Math.floor(remainingSeconds / seconds);
|
||||
if (count > 0) {
|
||||
result.push(`${count}${unit}`);
|
||||
remainingSeconds -= count * seconds;
|
||||
}
|
||||
// Stop after two units have been added
|
||||
if (result.length === 2) break;
|
||||
}
|
||||
|
||||
// Return formatted result with at most two units
|
||||
return result.join(", ") + " ago";
|
||||
}
|
||||
|
||||
/**
|
||||
|
Reference in New Issue
Block a user