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

0% Statements 0/9
0% Branches 0/12
0% Functions 0/1
0% Lines 0/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                                                                                                   
import moment from 'moment';
import i18n from 'i18next';
 
export interface FormatDICOMTimeOptions {
  /**
   * Explicit output format. When provided it overrides the locale's
   * `Common:localTimeFormat`; when omitted the locale key is used.
   */
  strFormat?: string;
  /**
   * Output format used when the active locale does not define
   * `Common:localTimeFormat` (none of the shipped locales do today, so in
   * practice this is what renders). Defaults to `hh:mm A`.
   */
  fallbackFormat?: string;
  /** Returned when `time` is empty or cannot be parsed. Defaults to `''`. */
  invalidFallback?: string;
}
 
/**
 * Formats a DICOM time.
 *
 * @param time - Raw time string (e.g. `HH`, `HHmm`, `HHmmss`, `HHmmss.SSS`).
 * @param options - See {@link FormatDICOMTimeOptions}.
 * @returns The formatted time, or the resolved invalid fallback.
 *
 * @example
 * formatDICOMTime(time, { invalidFallback: '' });
 */
export function formatDICOMTime(time: string, options: FormatDICOMTimeOptions = {}): string {
  const { strFormat, fallbackFormat = 'hh:mm A', invalidFallback } = options;
 
  Iif (!time) {
    return invalidFallback ?? '';
  }
 
  const format = strFormat ?? i18n.t('Common:localTimeFormat', fallbackFormat);
  const locale = i18n.language || 'en';
  const parsed = moment(time, ['HH', 'HHmm', 'HHmmss', 'HHmmss.SSS'], true);
 
  // Unlike formatDICOMDate, there is no lenient reparse: a no-format
  // moment(time) treats the string as a date (e.g. "1430" -> year 1430), so an
  // unparseable time falls straight back rather than fabricating a wrong value.
  Iif (!parsed.isValid()) {
    return invalidFallback ?? '';
  }
 
  return parsed.locale(locale).format(format);
}