formatDate Function
December 21, 2025
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);
}
How It Works
- Accepts Date objects, strings, or timestamps.
- Uses
Intl.DateTimeFormatfor internationalization support. - Provides sensible defaults but allows customization.
Example Usage
// 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',
});
Common Patterns
// 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);
}
Use Cases
- Displaying blog post dates
- Showing timestamps in comments
- Formatting user registration dates
- Displaying event dates
- Creating readable timestamps
Notes
- Uses the browser's built-in internationalization API.
- Automatically handles timezone based on user's locale.
- For relative time ("2 hours ago"), consider libraries like
date-fnsordayjs. - The function is locale-aware and can be extended to support other locales.
A simple, flexible date formatting utility that works with any date format and provides consistent output.