52 lines
1.5 KiB
TypeScript
52 lines
1.5 KiB
TypeScript
export const formatCommentDate = (date: Date | number | string): string => {
|
|
// Convert input to Date object if it's not already
|
|
const inputDate = date instanceof Date ? date : new Date(date);
|
|
const now = new Date();
|
|
|
|
// Get time difference in seconds
|
|
const diffSeconds = Math.floor((now.getTime() - inputDate.getTime()) / 1000);
|
|
|
|
// Just now - less than a minute ago
|
|
if (diffSeconds < 60) {
|
|
return "just now";
|
|
}
|
|
|
|
// Minutes ago - less than an hour
|
|
const diffMinutes = Math.floor(diffSeconds / 60);
|
|
if (diffMinutes < 60) {
|
|
return `${diffMinutes} ${diffMinutes === 1 ? "min" : "mins"} ago`;
|
|
}
|
|
|
|
// Hours ago - less than a day
|
|
const diffHours = Math.floor(diffMinutes / 60);
|
|
if (diffHours < 24) {
|
|
return `${diffHours} ${diffHours === 1 ? "hour" : "hours"} ago`;
|
|
}
|
|
|
|
// Days ago - less than a week
|
|
const diffDays = Math.floor(diffHours / 24);
|
|
if (diffDays < 7) {
|
|
return `${diffDays} ${diffDays === 1 ? "day" : "days"} ago`;
|
|
}
|
|
|
|
// Weeks ago - less than a month
|
|
const diffWeeks = Math.floor(diffDays / 7);
|
|
if (diffWeeks < 4) {
|
|
return `${diffWeeks} ${diffWeeks === 1 ? "week" : "weeks"} ago`;
|
|
}
|
|
|
|
// Months ago - less than a year
|
|
const diffMonths = Math.floor(diffDays / 30);
|
|
if (diffMonths < 12) {
|
|
return `${diffMonths} ${diffMonths === 1 ? "month" : "months"} ago`;
|
|
}
|
|
|
|
// More than a year ago - show full date
|
|
const options: Intl.DateTimeFormatOptions = {
|
|
year: "numeric",
|
|
month: "long",
|
|
day: "numeric",
|
|
};
|
|
return inputDate.toLocaleDateString(undefined, options);
|
|
};
|