0

I have very irregular date formats, like the following:

["December 15th", "October 31st", "31 of October", "November 25th 2022", "22.10.2022", "15 November 2022", "9th of April 2023", "Friday 25 November 2022"]

I would like to format them to MM/DD/YYY, or another format that could then be formatted to a standard format.

I was hoping to get ideas about the best way of doing this in Javascript / Nodejs.

I'm also open to using an 3rd party API / train a ML model, or anything else.

Thanks.

I've tried the following:

  • cleanup step (remove ',', '.')
  • parsing with Date.parse()
  • creating a new Date() by feeding it the output of Date.parse()

ex:

let cleaned = "9th of April".replace("th", "").replace("of", "") // returns '9 april 2023'

let timestamp = Date.parse(cleaned);

let date = new Date(timestamp);

console.log(date);

Which is fine in this case, but not general purpose enough.

  • Maybe this 3rd party can help: https://momentjs.com/ – Miguel Hidalgo Oct 29 '22 at 18:42
  • Unless you want to write your own parser a library is probably your best bet. datefns is a more current competitor to momentjs. [datefns.parse()](https://date-fns.org/v2.29.3/docs/parse). But you'll still need to specify the format of the date you pass to it, there is no catch all to detect format. – pilchard Oct 29 '22 at 20:11
  • There is no point to `new Date(Date.parse(string))`, the result must be identical to `new Date(string)` per ECMA-262. Parsing strings without specifying the format (e.g. with *Date.parse*) is fraught and definitely not recommended as the string may be misinterpreted and different implementations may (and in practice do) give different results, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Oct 29 '22 at 23:36

0 Answers0