Format dates consistently across your application with a simple utility function.
export function formatDate(
date: Date | string | number,
options: Intl.DateTimeFormatOptions = {
year: 'numeric',
month: 'long',
day: 'numeric',
}
): string {
const dateObj = typeof date === 'string' || typeof date === 'number'
? new Date(date)
: date;
return new Intl.DateTimeFormat('en-US', options).format(dateObj);
}Formatting dates consistently is crucial for a good user experience. This utility function provides a clean way to format dates in various styles.
export function formatDate(
date: Date | string | number,
options: Intl.DateTimeFormatOptions = {
year: 'numeric',
month: 'long',
day: 'numeric',
}
): string {
const dateObj = typeof date === 'string' || typeof date === 'number'
? new Date(date)
: date;
return new Intl.DateTimeFormat('en-US', options).format(dateObj);
}
Intl.DateTimeFormat for internationalization support.// Default format: "April 28, 2025"
formatDate(new Date());
// Custom format: "04/28/2025"
formatDate(new Date(), {
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
// Short format: "Apr 28, 2025"
formatDate(new Date(), {
year: 'numeric',
month: 'short',
day: 'numeric',
});
// With time: "April 28, 2025, 3:45 PM"
formatDate(new Date(), {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
});
// Relative time (requires additional logic)
function formatRelativeTime(date: Date): string {
const now = new Date();
const diff = now.getTime() - date.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days === 0) return 'Today';
if (days === 1) return 'Yesterday';
if (days < 7) return `${days} days ago`;
return formatDate(date);
}
date-fns or dayjs.A simple, flexible date formatting utility that works with any date format and provides consistent output.