All files / src/utils/date dateFormat.ts

100% Statements 32/32
100% Branches 31/31
100% Functions 6/6
100% Lines 32/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179                      3x                       44x 1x   43x 43x                                   7x 1x     6x     6x   7x                                 5x 1x     4x       4x               5x                               31x 1x     30x     30x   31x                                 5x 1x     4x     4x 3x             1x                                           3x 1x   2x     3x 1x     2x    
/**
 * Date Formatting Utilities
 * Story 1.17, Task 2b: Date/time formatting with date-fns locales
 *
 * Supports German (de) and English (en) locales with fallback to German as default
 */
 
import { format, formatDistance, formatDistanceToNow, parseISO, parse, isValid } from 'date-fns';
import { de, enUS, type Locale } from 'date-fns/locale';
 
// Supported locales
const locales = {
  de,
  en: enUS,
} as const;
 
type SupportedLocale = keyof typeof locales;
 
/**
 * Get date-fns locale object for a given locale code
 * Falls back to German (de) for unsupported locales or missing locale
 */
function getLocale(locale?: string | null): Locale {
  if (!locale) {
    return locales.de;
  }
  const normalizedLocale = locale.toLowerCase() as SupportedLocale;
  return locales[normalizedLocale] || locales.de;
}
 
/**
 * Format a date according to locale
 *
 * @param date - Date to format
 * @param locale - Locale code ('de' or 'en')
 * @param formatString - Optional custom format string (date-fns format)
 * @returns Formatted date string
 * @throws Error if date is invalid
 *
 * @example
 * formatDate(new Date('2024-03-15'), 'de') // "15. März 2024"
 * formatDate(new Date('2024-03-15'), 'en') // "March 15, 2024"
 * formatDate(new Date('2024-03-15'), 'de', 'dd.MM.yyyy') // "15.03.2024"
 */
export function formatDate(date: Date, locale: string, formatString?: string): string {
  if (!isValid(date)) {
    throw new Error('Invalid date provided');
  }
 
  const localeObj = getLocale(locale);
 
  // Default format strings per locale
  const defaultFormat = locale === 'en' ? 'MMMM d, yyyy' : 'd. MMMM yyyy';
 
  return format(date, formatString || defaultFormat, { locale: localeObj });
}
 
/**
 * Format a time according to locale
 *
 * @param date - Date to format
 * @param locale - Locale code ('de' or 'en')
 * @param includeSeconds - Whether to include seconds
 * @returns Formatted time string
 * @throws Error if date is invalid
 *
 * @example
 * formatTime(new Date('2024-03-15T14:30:00'), 'de') // "14:30"
 * formatTime(new Date('2024-03-15T14:30:00'), 'en') // "2:30 PM"
 */
export function formatTime(date: Date, locale: string, includeSeconds = false): string {
  if (!isValid(date)) {
    throw new Error('Invalid date provided');
  }
 
  const localeObj = getLocale(locale);
 
  // German uses 24-hour format, English uses 12-hour format
  const timeFormat =
    locale === 'en'
      ? includeSeconds
        ? 'h:mm:ss a'
        : 'h:mm a'
      : includeSeconds
        ? 'HH:mm:ss'
        : 'HH:mm';
 
  return format(date, timeFormat, { locale: localeObj });
}
 
/**
 * Format a date and time according to locale
 *
 * @param date - Date to format
 * @param locale - Locale code ('de' or 'en')
 * @returns Formatted date and time string
 * @throws Error if date is invalid
 *
 * @example
 * formatDateTime(new Date('2024-03-15T14:30:00'), 'de') // "15. März 2024, 14:30"
 * formatDateTime(new Date('2024-03-15T14:30:00'), 'en') // "March 15, 2024, 2:30 PM"
 */
export function formatDateTime(date: Date, locale: string): string {
  if (!isValid(date)) {
    throw new Error('Invalid date provided');
  }
 
  const localeObj = getLocale(locale);
 
  // Combined date and time format
  const dateTimeFormat = locale === 'en' ? 'MMMM d, yyyy, h:mm a' : 'd. MMMM yyyy, HH:mm';
 
  return format(date, dateTimeFormat, { locale: localeObj });
}
 
/**
 * Format a relative time (e.g., "2 hours ago", "in 3 days")
 *
 * @param date - Date to format
 * @param locale - Locale code ('de' or 'en')
 * @param baseDate - Optional base date for comparison (defaults to now)
 * @returns Relative time string
 * @throws Error if date is invalid
 *
 * @example
 * formatRelativeTime(new Date('2024-03-15T12:00:00'), 'de', new Date('2024-03-15T14:30:00'))
 * // "vor 2 Stunden" (2 hours ago)
 */
export function formatRelativeTime(date: Date, locale: string, baseDate?: Date): string {
  if (!isValid(date)) {
    throw new Error('Invalid date provided');
  }
 
  const localeObj = getLocale(locale);
 
  // If baseDate is provided, calculate the distance between dates
  if (baseDate) {
    return formatDistance(date, baseDate, {
      locale: localeObj,
      addSuffix: true,
      includeSeconds: false,
    });
  }
 
  return formatDistanceToNow(date, {
    locale: localeObj,
    addSuffix: true,
    includeSeconds: false,
  });
}
 
/**
 * Parse a date string into a Date object
 *
 * @param dateString - Date string to parse
 * @param formatString - Optional format string for parsing (defaults to ISO 8601)
 * @returns Parsed Date object
 * @throws Error if date string is invalid
 *
 * @example
 * parseDate('2024-03-15T14:30:00Z') // Date object
 * parseDate('15.03.2024', 'dd.MM.yyyy') // Date object
 */
export function parseDate(dateString: string, formatString?: string): Date {
  let parsedDate: Date;
 
  if (formatString) {
    parsedDate = parse(dateString, formatString, new Date());
  } else {
    parsedDate = parseISO(dateString);
  }
 
  if (!isValid(parsedDate)) {
    throw new Error(`Invalid date string: ${dateString}`);
  }
 
  return parsedDate;
}