UNPKG

datemapper

Version:

A lightweight date utility for format conversion, validation, and date manipulation.

61 lines (54 loc) 2.12 kB
/** * Converts date format placeholders between Unix-style (`%Y-%m-%d`) and Moment.js (`YYYY-MM-DD`). * * - If `toNewFormat` is `true`, it converts from Unix-style (`%Y`, `%m`, etc.) to Moment.js format (`YYYY`, `MM`, etc.). * - If `toNewFormat` is `false`, it converts from Moment.js format back to Unix-style. * - Ensures that only valid placeholders are present before conversion. * * @param format - The date format string containing placeholders. * @param toNewFormat - Boolean flag to control conversion direction. * - `true` (default): Convert Unix-style (`%Y-%m-%d`) to Moment.js (`YYYY-MM-DD`). * - `false`: Convert Moment.js (`YYYY-MM-DD`) back to Unix-style (`%Y-%m-%d`). * @returns The reformatted date format string. * @throws {Error} If the format contains unrecognized placeholders. */ const convertDateFormat = (format: string, toNewFormat: boolean = true): string => { // Define mappings for valid conversions const formatMap: Record<string, string> = toNewFormat ? { "%Y": "YYYY", // Year "%m": "MM", // Month "%d": "DD", // Day "%U": "ww", // Week of the year "%H": "HH", // Hour (24-hour format) "%M": "mm", // Minute "%S": "ss" // Second } : { YYYY: "%Y", MM: "%m", DD: "%d", ww: "%U", HH: "%H", mm: "%M", ss: "%S" }; // Extract valid keys for validation const validKeys = Object.keys(formatMap); // Validate format: Ensure all placeholders are known const regex = toNewFormat ? /%[YmdUHMS]/g : /\b(?:YYYY|MM|DD|ww|HH|mm|ss)\b/g; const foundTokens = format.match(regex); if (foundTokens) { for (const token of foundTokens) { if (!validKeys.includes(token)) { throw new Error(`Invalid date format token detected: ${token}`); } } } // Replace placeholders in the format string using the mapping Object.keys(formatMap).forEach(key => { format = format.replace(new RegExp(key, "g"), formatMap[key]); }); return format; }; export default convertDateFormat;