0

I am trying to format a string date to yyyy-mm-dd. Typically, it comes as d/m/yyyy but regardless of the input, I want to have it as yyyy-mm-dd.

const date = new Date("13/10/2016");
const DateParsed = moment(date).format("YYYY-MM-DD");

const dateParsed2 = moment("13/10/2016").format('YYYY-MM-DD')

I was expecting 2016-10-13 but I'm getting 0000-00-00 instead.

VincenzoC
  • 30,117
  • 12
  • 90
  • 112
Nie Selam
  • 1,343
  • 2
  • 24
  • 56
  • Not moment’s fault. Execute `new Date("13/10/2016")` on the console, and see what that says. – misorude Dec 05 '18 at 14:40
  • Possible duplicate of https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript – misorude Dec 05 '18 at 14:41
  • 1
    Which moment version are you using? With moment `v2.22.2` in Chrome on Win 10 I get `Invalid date`. As stated in the linked question `"13/10/2016"` is not a valid input for `Date.parse`, you can use [`moment(String, String)`](http://momentjs.com/docs/#/parsing/string-format/) instead. – VincenzoC Dec 05 '18 at 19:19
  • @VincenzoC thank you! It worked. You can answer it so I mark it as an answer, thank you. – Nie Selam Dec 06 '18 at 03:59

1 Answers1

1

Since your input is not in a format recognized by Date.parse, I suggest to use moment(String, String) instead of new Date().

Here a live sample:

const date = "13/10/2016";
const DateParsed = moment(date, 'DD/MM/YYYY').format("YYYY-MM-DD");
console.log(DateParsed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
VincenzoC
  • 30,117
  • 12
  • 90
  • 112