export function parseDateFromFormat(str: string, format: string): Date | null { if (!str) return null; const sepMatch = format.match(/[^A-Z]/i); if (!sepMatch) return null; const sep = sepMatch[0]; if (!str.includes(sep)) return null; const parts = str.split(sep); const fmtParts = format.split(sep); let day: number | null = null; let month: number | null = null; let year: number | null = null; for (let i = 0; i < fmtParts.length; i++) { const f = fmtParts[i]; const v = parts[i]; if (!v) return null; if (f === "DD") { if (v.length !== 2) return null; day = Number(v); } if (f === "MM") { if (v.length !== 2) return null; month = Number(v) - 1; } if (f === "YYYY") { if (v.length !== 4) return null; year = Number(v); } } if (day == null || month == null || year == null) return null; const d = new Date(year, month, day); if ( d.getFullYear() !== year || d.getMonth() !== month || d.getDate() !== day ) return null; return d; } export function formatDateToFormat(date: Date, format: string): string { if (!date) return ""; const day = String(date.getDate()).padStart(2, "0"); const month = String(date.getMonth() + 1).padStart(2, "0"); const year = date.getFullYear(); switch (format) { case "DD/MM/YYYY": return `${day}/${month}/${year}`; case "MM/DD/YYYY": return `${month}/${day}/${year}`; case "YYYY/MM/DD": return `${year}/${month}/${day}`; case "YYYY.MM.DD": return `${year}.${month}.${day}`; case "DD.MM.YYYY": return `${day}.${month}.${year}`; default: return `${day}/${month}/${year}`; } } export function parseRangeFromFormat( input: string, format: string, isRange: boolean, separator: string ) { if (!isRange) { return { first: parseDateFromFormat(input, format), second: null }; } if (!input.includes(separator)) { return { first: parseDateFromFormat(input, format), second: null }; } const [firstRaw, secondRaw] = input.split(separator); const first = parseDateFromFormat(firstRaw, format); const second = secondRaw ? parseDateFromFormat(secondRaw, format) : null; return { first, second }; } export function normalizeDateRange( first: Date | null, second: Date | null ): [Date | null, Date | null] { if (first && second && first.getTime() > second.getTime()) { return [second, first]; } return [first, second]; }