24 lines
743 B
TypeScript
24 lines
743 B
TypeScript
import { formatDistanceToNow, format, differenceInDays } from 'date-fns';
|
|
|
|
/**
|
|
* Formats a date as relative time (e.g., "2 hours ago") if within 7 days,
|
|
* otherwise returns an absolute date (e.g., "Mar 15").
|
|
*/
|
|
export function formatRelativeTime(date: Date | string): string {
|
|
const d = typeof date === 'string' ? new Date(date) : date;
|
|
const daysDiff = differenceInDays(new Date(), d);
|
|
|
|
if (daysDiff <= 7) {
|
|
return formatDistanceToNow(d, { addSuffix: true });
|
|
}
|
|
return format(d, 'MMM d');
|
|
}
|
|
|
|
/**
|
|
* Formats a date as an absolute timestamp (e.g., "Mar 15, 2024, 3:30 PM").
|
|
*/
|
|
export function formatAbsoluteTime(date: Date | string): string {
|
|
const d = typeof date === 'string' ? new Date(date) : date;
|
|
return format(d, 'PPpp');
|
|
}
|