Date Formatter
Format dates with customizable patterns and locale support
Description
A date formatting utility that supports custom patterns, multiple locales, and timezone handling. Provides consistent date formatting across the application.
Features
- Custom format patterns
- Locale support
- Timezone conversion
- Relative time formatting
Code
type FormatPattern = 'short' | 'long' | 'iso' | 'relative' | string;class DateFormatter { private locale: string; private timezone: string; constructor(locale: string = 'en-US', timezone: string = 'UTC') { this.locale = locale; this.timezone = timezone; } format(date: Date, pattern: FormatPattern = 'short'): string { if (pattern === 'short') { return date.toLocaleDateString(this.locale, { timeZone: this.timezone }); } if (pattern === 'long') { return date.toLocaleString(this.locale, { timeZone: this.timezone, dateStyle: 'full', timeStyle: 'long' }); } if (pattern === 'iso') { return date.toISOString(); } if (pattern === 'relative') { return this.formatRelative(date); } return this.formatCustom(date, pattern); } private formatRelative(date: Date): string { const now = new Date(); const diff = now.getTime() - date.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); if (days > 0) return `${days} day${days > 1 ? 's' : ''} ago`; if (hours > 0) return `${hours} hour${hours > 1 ? 's' : ''} ago`; if (minutes > 0) return `${minutes} minute${minutes > 1 ? 's' : ''} ago`; return 'just now'; } private formatCustom(date: Date, pattern: string): string { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); return pattern .replace('YYYY', String(year)) .replace('MM', month) .replace('DD', day) .replace('HH', hours) .replace('mm', minutes) .replace('ss', seconds); }}export default DateFormatter;
import DateFormatter from './dateFormatter';const formatter = new DateFormatter('en-US', 'UTC');const date = new Date('2024-01-15T10:30:00Z');console.log('Short:', formatter.format(date, 'short'));console.log('Long:', formatter.format(date, 'long'));console.log('ISO:', formatter.format(date, 'iso'));console.log('Relative:', formatter.format(date, 'relative'));console.log('Custom:', formatter.format(date, 'YYYY-MM-DD HH:mm:ss'));
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.