|
| 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) { |
| 20 | + return |
| 21 | + } |
| 22 | + |
| 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 |
| 32 | +} |
0 commit comments