All files / src/lib date-utils.js

50% Statements 24/48
100% Branches 2/2
33.33% Functions 1/3
50% Lines 24/48

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 49193x 193x 193x 193x 193x 193x 5x 5x 193x 193x 193x 193x 193x 193x 193x 193x                             193x 193x 193x 193x 193x 193x 193x 193x                      
/**
 * Formats a date to ISO-like format "YYYY-MM-DD HH:mm".
 * @param {string | number | Date} dateInput
 * @returns {string}
 */
export function formatDate(dateInput) {
  return new Date(dateInput).toISOString().substring(0, 16).replace('T', ' ');
}
 
/**
 * Formats a date to localized display format (e.g. "Feb 5, 2027, 14:16 UTC").
 * Returns undefined when the input is nullish.
 * @param {Date | undefined | null} date
 * @returns {string | undefined}
 */
export function formatDateLocalized(date) {
  if (date == null) {
    return undefined;
  }
  return date.toLocaleString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
    timeZone: 'UTC',
    timeZoneName: 'short',
  });
}
 
/**
 * Safely converts various date inputs (ISO string, timestamp, Date) to a Date instance.
 * Returns undefined for null/undefined or invalid values.
 * @param {string | number | Date | undefined | null} dateInput
 * @returns {Date | undefined}
 */
export function toDate(dateInput) {
  if (dateInput == null) {
    return undefined;
  }
  try {
    const date = new Date(dateInput);
    return Number.isNaN(date.getTime()) ? undefined : date;
  } catch {
    return undefined;
  }
}