I have an example datetime string "Today, Fri May 12 2023 at 07:00:00, we go swimming". I use the new Date(string) and it gives invalid date.
Is there regex script to convert that string to valid date?
I have an example datetime string "Today, Fri May 12 2023 at 07:00:00, we go swimming". I use the new Date(string) and it gives invalid date.
Is there regex script to convert that string to valid date?
3
Answers
You can of course convert a string if you know it follows that exact form. But I suppose that’s not the case and you’re looking for the ability to parse various sentences in free-form english that contain date and time information.
Parsing free-form language can’t be done by a classic algorithm, with or without a regex. Humans can do so, and an AI can be trained to do so as well. You can send the sentence to ChatGPT’s API for example, with a prompt asking it to return the date in standardized form. Even then, there might be sentences which are worded in a confusing way and would be interpretted wrong.
Once the regex has matched the string, use the following code to convert it to a valid date:
The string will be parsed into a DateTime object using the
DateTime.ParseExact()
method in this code. The ‘CultureInfo.InvariantCulture’ argument specifies that the date should be parsed using the invariant culture, which is the culture that is independent of the user’s location.I’d suggest sanitizing your input(s), then using a dedicated datetime module such as luxon to parse the result.
We’d split and filter the string using a custom
sanitizeInput
function then use DateTime.fromFormat to parse it.