Add: relativeTime func to utils
This commit is contained in:
parent
0ce4dc12bd
commit
4c094920fd
1 changed files with 39 additions and 0 deletions
|
@ -4,3 +4,42 @@ import { twMerge } from "tailwind-merge"
|
|||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
|
||||
export function relativeTime(dtString: string): string {
|
||||
/**
|
||||
* Convert a datetime string to a relative time string.
|
||||
*
|
||||
* Args:
|
||||
* dtString (string): A datetime string in the format "YYYY-MM-DDTHH:MM:SS+HHMM"
|
||||
*
|
||||
* Returns:
|
||||
* string: A relative time string, e.g. "1 Hour ago", "2 Weeks ago", etc.
|
||||
*/
|
||||
const dt = new Date(dtString);
|
||||
const now = new Date();
|
||||
const diff = now.getTime() - dt.getTime();
|
||||
|
||||
const seconds = Math.floor(diff / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
const weeks = Math.floor(days / 7);
|
||||
const months = Math.floor(days / 30);
|
||||
|
||||
if (months >= 3) {
|
||||
return dt.toISOString().split('T')[0];
|
||||
} else if (months > 0) {
|
||||
return `${months} month${months > 1 ? 's' : ''} ago`;
|
||||
} else if (weeks > 0) {
|
||||
return `${weeks} week${weeks > 1 ? 's' : ''} ago`;
|
||||
} else if (days > 0) {
|
||||
return `${days} day${days > 1 ? 's' : ''} ago`;
|
||||
} else if (hours > 0) {
|
||||
return `${hours} hour${hours > 1 ? 's' : ''} ago`;
|
||||
} else if (minutes > 0) {
|
||||
return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
|
||||
} else {
|
||||
return `${seconds} second${seconds > 1 ? 's' : ''} ago`;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue