@ministryofjustice/hmpps-digital-prison-reporting-frontend
Version:
The Digital Prison Reporting Frontend contains templates and code to help display data effectively in UI applications.
93 lines (89 loc) • 2.57 kB
JavaScript
;
var dayjs = require('dayjs');
var customParseFormat = require('../../_virtual/customParseFormat.js');
dayjs.extend(customParseFormat);
/**
* --------------------------------------------
* 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);
}
exports.UI_INPUT_FORMATS = UI_INPUT_FORMATS;
exports.apiDateToUi = apiDateToUi;
exports.apiTimestampToUiDateTime = apiTimestampToUiDateTime;
exports.formatDateOrUnset = formatDateOrUnset;
exports.isValidUiDate = isValidUiDate;
exports.todayAsUiDateTime = todayAsUiDateTime;
exports.uiDateToApi = uiDateToApi;
//# sourceMappingURL=dateHelper.js.map