|
1 |
| -export const getLocalDateFromString = (string, locale, time) => { |
2 |
| - const date = new Date(2013, 11, 31, 17, 19, 22) |
3 |
| - let regex = time ? date.toLocaleString(locale) : date.toLocaleDateString(locale) |
4 |
| - regex = regex |
5 |
| - .replace('2013', '(?<year>[0-9]{2,4})') |
6 |
| - .replace('12', '(?<month>[0-9]{1,2})') |
7 |
| - .replace('31', '(?<day>[0-9]{1,2})') |
8 |
| - if (time) { |
9 |
| - regex = regex |
10 |
| - .replace('5', '(?<hour>[0-9]{1,2})') |
11 |
| - .replace('17', '(?<hour>[0-9]{1,2})') |
12 |
| - .replace('19', '(?<minute>[0-9]{1,2})') |
13 |
| - .replace('22', '(?<second>[0-9]{1,2})') |
14 |
| - .replace('PM', '(?<ampm>[A-Z]{2})') |
15 |
| - } |
16 |
| - |
17 |
| - const rgx = new RegExp(`${regex}`) |
18 |
| - const partials = string.match(rgx) |
19 |
| - if (partials === null) { |
| 1 | +// Helper function to generate multiple date format patterns |
| 2 | +const generateDatePatterns = (locale, includeTime) => { |
| 3 | + const referenceDate = new Date(2013, 11, 31, 17, 19, 22) |
| 4 | + const patterns = [] |
| 5 | + |
| 6 | + try { |
| 7 | + // Get the standard locale format |
| 8 | + const standardFormat = includeTime ? |
| 9 | + referenceDate.toLocaleString(locale) : |
| 10 | + referenceDate.toLocaleDateString(locale) |
| 11 | + |
| 12 | + patterns.push(standardFormat) |
| 13 | + } catch { |
| 14 | + // Fallback to default locale if invalid locale provided |
| 15 | + const standardFormat = includeTime ? |
| 16 | + referenceDate.toLocaleString('en-US') : |
| 17 | + referenceDate.toLocaleDateString('en-US') |
| 18 | + patterns.push(standardFormat) |
| 19 | + } |
| 20 | + |
| 21 | + // Generate common alternative formats by replacing separators |
| 22 | + const separators = ['/', '-', '.', ' '] |
| 23 | + const standardFormat = patterns[0] |
| 24 | + |
| 25 | + // Detect the original separator |
| 26 | + let originalSeparator = '/' // default |
| 27 | + if (standardFormat.includes('/')) { |
| 28 | + originalSeparator = '/' |
| 29 | + } else if (standardFormat.includes('-')) { |
| 30 | + originalSeparator = '-' |
| 31 | + } else if (standardFormat.includes('.')) { |
| 32 | + originalSeparator = '.' |
| 33 | + } |
| 34 | + |
| 35 | + for (const sep of separators) { |
| 36 | + if (sep !== originalSeparator) { |
| 37 | + const altFormat = standardFormat.replace(new RegExp(`\\${originalSeparator}`, 'g'), sep) |
| 38 | + patterns.push(altFormat) |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return patterns |
| 43 | +} |
| 44 | + |
| 45 | +// Helper function to build regex pattern for date parsing |
| 46 | +const buildDateRegexPattern = (formatString, includeTime) => { |
| 47 | + let regexPattern = formatString |
| 48 | + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') |
| 49 | + .replace('2013', '(?<year>\\d{2,4})') |
| 50 | + .replace('12', '(?<month>\\d{1,2})') |
| 51 | + .replace('31', '(?<day>\\d{1,2})') |
| 52 | + |
| 53 | + if (includeTime) { |
| 54 | + regexPattern = regexPattern |
| 55 | + .replace(/17|5/g, '(?<hour>\\d{1,2})') |
| 56 | + .replace('19', '(?<minute>\\d{1,2})') |
| 57 | + .replace('22', '(?<second>\\d{1,2})') |
| 58 | + .replace(/AM|PM/gi, '(?<ampm>[APap][Mm])') |
| 59 | + } |
| 60 | + |
| 61 | + return regexPattern |
| 62 | +} |
| 63 | + |
| 64 | +// Helper function to try parsing with multiple patterns |
| 65 | +const tryParseWithPatterns = (dateString, patterns, includeTime) => { |
| 66 | + for (const pattern of patterns) { |
| 67 | + const regexPattern = buildDateRegexPattern(pattern, includeTime) |
| 68 | + const regex = new RegExp(`^${regexPattern}$`) |
| 69 | + const match = dateString.trim().match(regex) |
| 70 | + |
| 71 | + if (match?.groups) { |
| 72 | + return match.groups |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return null |
| 77 | +} |
| 78 | + |
| 79 | +// Helper function to validate date components |
| 80 | +const validateDateComponents = (month, day) => { |
| 81 | + const parsedMonth = Number.parseInt(month, 10) - 1 |
| 82 | + const parsedDay = Number.parseInt(day, 10) |
| 83 | + |
| 84 | + return parsedMonth >= 0 && parsedMonth <= 11 && parsedDay >= 1 && parsedDay <= 31 |
| 85 | +} |
| 86 | + |
| 87 | +// Helper function to convert 12-hour to 24-hour format |
| 88 | +const convertTo24Hour = (hour, ampm) => { |
| 89 | + const parsedHour = Number.parseInt(hour, 10) |
| 90 | + |
| 91 | + if (!ampm) { |
| 92 | + return parsedHour |
| 93 | + } |
| 94 | + |
| 95 | + const isPM = ampm.toLowerCase() === 'pm' |
| 96 | + |
| 97 | + if (isPM && parsedHour !== 12) { |
| 98 | + return parsedHour + 12 |
| 99 | + } |
| 100 | + |
| 101 | + if (!isPM && parsedHour === 12) { |
| 102 | + return 0 |
| 103 | + } |
| 104 | + |
| 105 | + return parsedHour |
| 106 | +} |
| 107 | + |
| 108 | +// Helper function to validate time components |
| 109 | +const validateTimeComponents = (hour, minute, second) => { |
| 110 | + return hour >= 0 && hour <= 23 && |
| 111 | + minute >= 0 && minute <= 59 && |
| 112 | + second >= 0 && second <= 59 |
| 113 | +} |
| 114 | + |
| 115 | +// Helper function to create date with time |
| 116 | +const createDateWithTime = groups => { |
| 117 | + const { year, month, day, hour, minute, second, ampm } = groups |
| 118 | + |
| 119 | + const parsedYear = Number.parseInt(year, 10) |
| 120 | + const parsedMonth = Number.parseInt(month, 10) - 1 |
| 121 | + const parsedDay = Number.parseInt(day, 10) |
| 122 | + const parsedHour = convertTo24Hour(hour, ampm) |
| 123 | + const parsedMinute = Number.parseInt(minute, 10) || 0 |
| 124 | + const parsedSecond = Number.parseInt(second, 10) || 0 |
| 125 | + |
| 126 | + if (!validateTimeComponents(parsedHour, parsedMinute, parsedSecond)) { |
| 127 | + return 'invalid' |
| 128 | + } |
| 129 | + |
| 130 | + return new Date(parsedYear, parsedMonth, parsedDay, parsedHour, parsedMinute, parsedSecond) |
| 131 | +} |
| 132 | + |
| 133 | +// Helper function to create date without time |
| 134 | +const createDateOnly = groups => { |
| 135 | + const { year, month, day } = groups |
| 136 | + |
| 137 | + const parsedYear = Number.parseInt(year, 10) |
| 138 | + const parsedMonth = Number.parseInt(month, 10) - 1 |
| 139 | + const parsedDay = Number.parseInt(day, 10) |
| 140 | + |
| 141 | + return new Date(parsedYear, parsedMonth, parsedDay) |
| 142 | +} |
| 143 | + |
| 144 | +/** |
| 145 | + * Parses a date string using locale-aware patterns and returns a Date object. |
| 146 | + * |
| 147 | + * This function generates multiple date format patterns based on the provided locale |
| 148 | + * and attempts to parse the input string using these patterns. It supports various |
| 149 | + * date separators (/, -, ., space) and handles both date-only and date-time formats. |
| 150 | + * |
| 151 | + * @param {string} dateString - The date string to parse (e.g., "12/31/2023", "31-12-2023") |
| 152 | + * @param {string} [locale='en-US'] - The locale to use for date format patterns (e.g., 'en-US', 'en-GB', 'de-DE') |
| 153 | + * @param {boolean} [includeTime=false] - Whether to include time parsing in the pattern matching |
| 154 | + * @returns {Date|string|undefined} A Date object if parsing succeeds, 'invalid' for malformed dates, undefined for empty input |
| 155 | + */ |
| 156 | +export const getLocalDateFromString = (dateString, locale = 'en-US', includeTime = false) => { |
| 157 | + // Input validation |
| 158 | + if (!dateString || typeof dateString !== 'string') { |
20 | 159 | return
|
21 | 160 | }
|
22 | 161 |
|
23 |
| - const newDate = partials.groups && |
24 |
| - (time ? |
25 |
| - new Date(Number(partials.groups.year, 10), Number(partials.groups.month, 10) - 1, Number(partials.groups.day), partials.groups.ampm ? |
26 |
| - (partials.groups.ampm === 'PM' ? |
27 |
| - Number(partials.groups.hour) + 12 : |
28 |
| - Number(partials.groups.hour)) : |
29 |
| - Number(partials.groups.hour), Number(partials.groups.minute), Number(partials.groups.second)) : |
30 |
| - new Date(Number(partials.groups.year), Number(partials.groups.month) - 1, Number(partials.groups.day))) |
31 |
| - return newDate |
| 162 | + // Generate multiple format patterns to try |
| 163 | + const patterns = generateDatePatterns(locale, includeTime) |
| 164 | + |
| 165 | + // Try parsing with different patterns |
| 166 | + const groups = tryParseWithPatterns(dateString, patterns, includeTime) |
| 167 | + |
| 168 | + if (!groups) { |
| 169 | + return 'invalid' |
| 170 | + } |
| 171 | + |
| 172 | + // Validate date components |
| 173 | + const { month, day } = groups |
| 174 | + if (!validateDateComponents(month, day)) { |
| 175 | + return 'invalid' |
| 176 | + } |
| 177 | + |
| 178 | + // Create and return appropriate date object |
| 179 | + return includeTime ? createDateWithTime(groups) : createDateOnly(groups) |
32 | 180 | }
|
0 commit comments