-1

I'm using Moment JS to try and convert a human readable date into something more useful for a computer/JS to understand, given the following Strings as example, my Moment JS doesn't appear to convert them:

const exampleDate = '1st January 2019'
moment(exampleDate).format('DD-MM-YYYY')

It returns Invalid Date, why?

Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • Does this answer your question? [Parse string to date with moment.js](https://stackoverflow.com/questions/22184747/parse-string-to-date-with-moment-js) – Heretic Monkey Feb 11 '20 at 21:18

1 Answers1

2

You need to "tell" moment from which format you want to create a date (second argument).

const exampleDate = '1st January 2019'
moment(exampleDate, 'Do MMMM YYYY').format('DD-MM-YYYY');

Link to JS Fiddle

KiwixLV
  • 226
  • 1
  • 5
  • 1
    Since the date is `'1st'`, you should use `Do` instead of `DD`. – gen_Eric Feb 11 '20 at 21:15
  • 1
    Yes, you're right, but moment will still parse it just fine if there is only one space between day and month e.g. "1LongStringHere January". I'll update my answer to not cause confusion, thanks. – KiwixLV Feb 11 '20 at 21:26