This commit is contained in:
parent
1faa97b332
commit
bd4f49205b
@ -1,28 +1,41 @@
|
|||||||
/**
|
/**
|
||||||
* This function returns the time ago of the input date
|
* 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
|
* @returns the format of the time ago
|
||||||
*/
|
*/
|
||||||
export function timeAgo(input: Date | number) {
|
export function timeAgo(input: number) {
|
||||||
const date = input instanceof Date ? input : new Date(input);
|
const inputDate = new Date(input).getTime(); // Convert input to a Date object if it's not already
|
||||||
const formatter = new Intl.RelativeTimeFormat("en");
|
const now = new Date().getTime();
|
||||||
const ranges: { [key: string]: number } = {
|
const deltaSeconds = Math.floor((now - inputDate) / 1000); // Get time difference in seconds
|
||||||
year: 3600 * 24 * 365,
|
|
||||||
month: 3600 * 24 * 30,
|
if (deltaSeconds < 60) {
|
||||||
week: 3600 * 24 * 7,
|
return "just now";
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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