All files / platform/ui-next/src/utils formatDICOMDate.ts

77.77% Statements 7/9
41.66% Branches 5/12
100% Functions 1/1
77.77% Lines 7/9

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                                                                                            5084x   5084x       5084x 5084x 5084x   5084x             5084x    
import moment from 'moment';
import i18n from 'i18next';
 
export interface FormatDICOMDateOptions {
  /**
   * Explicit output format. When provided it overrides the locale's
   * `Common:localDateFormat`; when omitted the locale key is used.
   */
  strFormat?: string;
  /**
   * Output format used only when the active locale does not define
   * `Common:localDateFormat` (8 of the shipped locales don't). Defaults to
   * `MMM D, YYYY`.
   */
  fallbackFormat?: string;
  /**
   * Returned when `date` is empty or cannot be parsed as a date at all. When
   * omitted, the prior behavior is preserved: a lenient `moment(date).format(...)`
   * is returned (which is `"Invalid date"` for unparseable input).
   */
  invalidFallback?: string;
}
 
/**
 * Formats a DICOM date.
 *
 * @param date - Raw date string (e.g. `YYYYMMDD` or `YYYY.MM.DD`).
 * @param options - See {@link FormatDICOMDateOptions}.
 * @returns The formatted date, or the resolved invalid fallback.
 *
 * @remarks
 * Migration: this previously took a positional format argument
 * (`formatDICOMDate(date, strFormat?)`). That format — and the additional
 * `fallbackFormat` / `invalidFallback` options — are now passed as a single
 * options object.
 *
 * @example
 * // Before (positional):
 * formatDICOMDate(date, 'YYYY-MM-DD');
 * // After (options object):
 * formatDICOMDate(date, { strFormat: 'YYYY-MM-DD' });
 *
 * @example
 * formatDICOMDate(date, { fallbackFormat: 'DD-MMM-YYYY', invalidFallback: '' });
 */
export function formatDICOMDate(date: string, options: FormatDICOMDateOptions = {}): string {
  const { strFormat, fallbackFormat = 'MMM D, YYYY', invalidFallback } = options;
 
  Iif (!date) {
    return invalidFallback ?? '';
  }
 
  const format = strFormat ?? i18n.t('Common:localDateFormat', fallbackFormat);
  const locale = i18n.language || 'en';
  const parsed = moment(date, ['YYYYMMDD', 'YYYY.MM.DD'], true);
 
  Iif (!parsed.isValid()) {
    // Honor an explicit fallback, otherwise preserve prior behavior (a lenient
    // parse, which formats valid non-DICOM strings and yields "Invalid date"
    // for unparseable input).
    return invalidFallback ?? moment(date).locale(locale).format(format);
  }
 
  return parsed.locale(locale).format(format);
}