diff --git a/src/filters/date.js b/src/filters/date.js new file mode 100644 index 000000000..2766d1381 --- /dev/null +++ b/src/filters/date.js @@ -0,0 +1,93 @@ +/** + * Checks if a given date is valid. + * + * @param {number|string|Date} date - The date to be checked. + * @returns {boolean} True if the date is valid, false otherwise. + * + * @example + * // returns true + * isValidDate(new Date()); + * + * @example + * // returns false + * isValidDate('invalid date'); + */ +export function isValidDate(date) { + return date && !isNaN(new Date(date).getTime()); +} + +/** + * Converts a given date to a specific format. + * + * @param {number|string|Date} date - The date to be formatted. + * @returns {string} The formatted date as a string in 'dd/mm/yyyy' format. If the provided date is not valid, an empty string is returned. + * + * @example + * // returns "02/12/2022" + * toDateFormat(new Date(2022, 11, 2)); + */ +export function toDateFormat(date) { + if (!isValidDate(date)) { + return ''; + } + return new Date(date).toLocaleDateString('es-ES', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + }); +} + +/** + * Converts a given date to a specific time format. + * + * @param {number|string|Date} date - The date to be formatted. + * @param {boolean} [showSeconds=false] - Whether to include seconds in the output format. + * @returns {string} The formatted time as a string in 'hh:mm:ss' format. If the provided date is not valid, an empty string is returned. If showSeconds is false, seconds are not included in the output format. + * + * @example + * // returns "00:00" + * toTimeFormat(new Date(2022, 11, 2)); + * + * @example + * // returns "00:00:00" + * toTimeFormat(new Date(2022, 11, 2), true); + */ +export function toTimeFormat(date, showSeconds = false) { + if (!isValidDate(date)) { + return ''; + } + return new Date(date).toLocaleDateString('es-ES', { + hour: '2-digit', + minute: '2-digit', + second: showSeconds ? '2-digit' : undefined, + }); +} + +/** + * Converts a given date to a specific date and time format. + * + * @param {number|string|Date} date - The date to be formatted. + * @param {boolean} [showSeconds=false] - Whether to include seconds in the output format. + * @returns {string} The formatted date as a string in 'dd/mm/yyyy, hh:mm:ss' format. If the provided date is not valid, an empty string is returned. If showSeconds is false, seconds are not included in the output format. + * + * @example + * // returns "02/12/2022, 00:00" + * toDateTimeFormat(new Date(2022, 11, 2)); + * + * @example + * // returns "02/12/2022, 00:00:00" + * toDateTimeFormat(new Date(2022, 11, 2), true); + */ +export function toDateTimeFormat(date, showSeconds = false) { + if (!isValidDate(date)) { + return ''; + } + return new Date(date).toLocaleDateString('es-ES', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: showSeconds ? '2-digit' : undefined, + }); +}