1

So I want to be able to have the user input a date as DD/MM/YYYY HH:mm then have it converted to MySQL datetime format for input in a database so I ran moment("20/04/2020 00:19", 'DD/MM/YYYY HH:mm',true).isValid() to test if I could do this and got back true to say it is correct so implemented it however I have a date invalid error whenever I try to do anything so tested it again in the console and well it gets a little weird:

enter image description here

Why does this happen it makes no sense to me... and is there a way I can do what I set out to do?

Lucas
  • 598
  • 9
  • 18
  • 4
    Because in the first line, you're specifying the input format. In the latter, you aren't and the input isn't a valid Date constructor string. – Andrew Li Apr 19 '20 at 23:39
  • 1
    You should have been getting a message in the console saying that the format is not a valid default format, so moment.js is falling back to the built–in parser, which likely assumes m/d/y and there is no 20th month. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) So use `moment("20/04/2020 00:19", 'DD/MM/YYYY HH:mm').format(...)`. – RobG Apr 19 '20 at 23:41
  • @AndrewLi that is literally the fastest answer I have ever had on StackOverflow ty – Lucas Apr 19 '20 at 23:47

1 Answers1

1

So in case, anyone else has the same issue Andrew Li's comment is correct and I didn't realize it is not valid in javascript built-in date format so to fix this you would have to use

moment("20/04/2020 00:19","DD/MM/YYYY HH:mm").format('DD-MM-YYYY HH:mm')

not:

moment("20/04/2020 00:19").format('DD/MM/YYYY HH:mm')

This therefore tells moment what format the date is already in so it can successfully change the formatting.

Lucas
  • 598
  • 9
  • 18
  • 1
    You really should always pass the format. Moment.js supports a limited sub–set of ISO 8601 and RFC 2822 formats by default. If the format isn't one of the defaults, the built–in parser will be used instead (which makes the moment.js parser redundant). – RobG Apr 20 '20 at 03:57