0

While using Angular 12 I have a date as a string in a very custom format, from which I need to produce a Date object. An example of the date strings I have are:

20280328
20271201

To the human eye, these are obviously in the format yyyyMMdd however none of the standard parse functions appear to understand this (not unexpected.)

Other than simply breaking the string using substring, is there a better way to interpret these strings into a Date object?

I was hoping to be able to provide a custom input format for the .parse() function, but this does not appear to be available.

Matt W
  • 11,753
  • 25
  • 118
  • 215
  • Does this answer your question? [Parsing a string to a date in JavaScript](https://stackoverflow.com/questions/5619202/parsing-a-string-to-a-date-in-javascript) – evolutionxbox Jul 01 '22 at 14:58
  • No, I've read that already and it is still automation attempting to identify the format from the input string. I need to specify the custom input format. – Matt W Jul 01 '22 at 15:09
  • Did you read all of the answers? – evolutionxbox Jul 01 '22 at 15:12
  • If you're referring to [this answer](https://stackoverflow.com/a/16235315/71376), no, I did not see that. Linking to that answer would have helped. – Matt W Jul 01 '22 at 15:21
  • I cannot link directly to an answer using the SO "duplicate" tool – evolutionxbox Jul 01 '22 at 15:22
  • Consider `let [c, y, m, d] = '20280328'.match(/\d\d/g); let date = new Date(c+y, m-1, d)`. – RobG Jul 02 '22 at 09:26
  • @MattW—that answer will parse the string as UTC, use it if that's what you want. But it's an inherently inefficient strategy to parse a string to create a another string that is then also parsed to create a date. Just parse the string once and give the parts directly to the Date constructor. – RobG Jul 02 '22 at 09:30

0 Answers0