Nodejs moment not able to convert string to date

Viewed 57

When I tried to run following code its returning Moment<Invalid date>

const moment = require('moment')
const date = "20210519"
const dateObj = moment(date, "yyyyMMdd",true)
console.log(dateObj)

How to convert this string to date object?

1 Answers

Changing the format string from "yyyyMMdd" to "YYYYMMDD" should fix the issue:

const date = "20210519"
const dateObj = moment(date, "YYYYMMDD",true)
console.log(dateObj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Some more parsing details are here: https://momentjs.com/docs/#/parsing/string-format/

Related