UNPKG

@ministryofjustice/hmpps-digital-prison-reporting-frontend

Version:

The Digital Prison Reporting Frontend contains templates and code to help display data effectively in UI applications.

85 lines (82 loc) 2.36 kB
import dayjs from 'dayjs'; import customParse from '../../_virtual/customParseFormat.js'; dayjs.extend(customParse); /** * -------------------------------------------- * Date formats * -------------------------------------------- */ const UI_INPUT_FORMATS = ['D/M/YYYY', 'DD/MM/YYYY']; const API_FORMAT = 'YYYY-MM-DD'; const UI_OUTPUT_FORMAT = 'DD/MM/YYYY'; const UI_DATE_TIME_FORMAT = 'DD/MM/YYYY HH:mm'; /** * -------------------------------------------- * Validation helpers * -------------------------------------------- */ function isValidUiDate(value) { if (!value) return false; return dayjs(value, [...UI_INPUT_FORMATS], true).isValid(); } /** * -------------------------------------------- * Transform helpers * -------------------------------------------- */ /** * DD/MM/YYYY -> YYYY-MM-DD * * @export * @param {string} [value] * @return {*} {(string | undefined)} */ function uiDateToApi(value) { if (!value) return undefined; const parsed = dayjs(value, [...UI_INPUT_FORMATS], true); return parsed.isValid() ? parsed.format(API_FORMAT) : undefined; } /** * YYYY-MM-DD -> DD/MM/YYYY * * @export * @param {string} [value] * @return {*} {(string | undefined)} */ function apiDateToUi(value) { if (!value) return undefined; const parsed = dayjs(value, API_FORMAT, true); return parsed.isValid() ? parsed.format(UI_OUTPUT_FORMAT) : undefined; } /** * TS -> DD/MM/YYYY HH:mm * * @export * @param {(string | Date)} [value] * @return {*} {(string | undefined)} */ function apiTimestampToUiDateTime(value) { if (!value) return undefined; const parsed = dayjs(value); return parsed.isValid() ? parsed.format(UI_DATE_TIME_FORMAT) : undefined; } /** * -------------------------------------------- * Display helpers * -------------------------------------------- */ function formatDateOrUnset(value) { if (!value) return 'unset'; const parsed = dayjs(value, [...UI_INPUT_FORMATS, API_FORMAT], true); return parsed.isValid() ? parsed.format(UI_OUTPUT_FORMAT) : 'unset'; } function todayAsUiDateTime() { return dayjs().format(UI_DATE_TIME_FORMAT); } export { UI_INPUT_FORMATS, apiDateToUi, apiTimestampToUiDateTime, formatDateOrUnset, isValidUiDate, todayAsUiDateTime, uiDateToApi }; //# sourceMappingURL=dateHelper.js.map