// Convert a custom format date string to the format "yyyy-mm-dd". export const convertToDateFormat = (date: string, format?: string): string => { const dateParts = date.split(/[-/]/); const formatParts = format ? format.split(/[-/]/) : ["yyyy", "mm", "dd"]; const dateObj: { [key: string]: number } = {}; const formattedDate: string[] = []; for (let i = 0; i < formatParts.length; i++) { dateObj[formatParts[i]] = dateParts[i] ? parseInt(dateParts[i], 10) : 0; } formattedDate.push(dateObj["yyyy"]?.toString() || "0000"); formattedDate.push( (dateObj["mm"] < 10 ? "0" : "") + (dateObj["mm"]?.toString() || "00"), ); formattedDate.push( (dateObj["dd"] < 10 ? "0" : "") + (dateObj["dd"]?.toString() || "00"), ); return formattedDate.join("-"); }; export const isValidDate = (date?: string, format = "yyyy-mm-dd"): boolean => { if (!date) return true; // Convert date to standard format const standardDate = convertToDateFormat(date, format); // Parse the standardized date const [yearStr, monthStr, dayStr] = standardDate.split("-"); const year = parseInt(yearStr, 10); const month = parseInt(monthStr, 10); const day = parseInt(dayStr, 10); // Validate month range if (month < 1 || month > 12) { return false; } // Check if day is valid for the month const daysInMonth = new Date(year, month, 0).getDate(); return day > 0 && day <= daysInMonth; };