I have been programming for years, yet I cannot even find a node library that can handle scenarios like this. I want to be able to parse potentially marlformed dates; is my only option really to parse with regex then reconstruct the date for the following examples?:
// invalid date
new Date('Apr 21, 2023,06:51 pm EDT');
// invalid date
new Date('Apr 21, 2023 06:51pm EDT');
// works
new Date('Apr 21, 2023 06:51 pm EDT');
// invalid date
new Date('7th Feb 2023'); // error
I have a super complicated regex pulling out the day, month, year, hour, minute, am/pm, and timezone, but is there a simpler approach to this?
2
Answers
Have you tried https://www.npmjs.com/package/any-date-parser ?
The best would be to have the date formatted in a standard way (ECMAScript’s Date Time String Format) at the source. If not possible, then indeed you’ll need to parse the input (or have a library do that for you).
Maybe you can build it up in steps, so it stays manageable? Or — if you decided to have the regex perform numerical validations — you could drop those validations and leave that for the Date constructor to deal with.
Here is a possible implementation with following characteristics:
W+
)Date.parse
.Of course, this is limited, and would need extension if more input formats need to be supported.