0

I am trying to convert this date into Mon Nov 26 2018 10:32:04 GMT (I am getting this data from the Api so i can't make changes to it)

I assume it is considering 26 as months thats why it is showing it as invalid date

Can Anyone help me with this. How to convert that date into the expected output i specified.

How to get

 var d = new Date("26-11-2018 10:32:04")
    return d; //Error: Invalid Date

expected Output: Mon Nov 26 2018 10:32:04 (IST)

2 Answers2

1

Use moment.js to parse the date.

moment("26-11-2018 10:32:04", "DD-MM-YYYY HH-mm-ss").toDate()

Alternatively, if you really don't want to use moment for whatever reason, you can use regex magic.

new Date("26-11-2018 10:32:04".replace(/^(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)$/, "$3-$2-$1T$4:$5:$6Z"))
Aplet123
  • 33,825
  • 1
  • 29
  • 55
-1

This is not a robust as @Yevgen answer but it also much simpler.

All I'm doing is removing the - and flipping the day and month values

const items = "26-11-2018 10:32:04".split('-')
new Date(`${items[1]} ${items[0]} ${items[2]}`)

This works for personal projects but I highly recommend using moment.js

Michael Warner
  • 3,879
  • 3
  • 21
  • 45