Zernst
Zernst

Reputation: 325

Converting String to Date using Moment.js returning Invalid Date

I am trying to add date data into Mongoose in my Node server, and this comes from a form that sends the date as a string. I have the following code:

    let ticket_data = req.body.ticket;
    console.log(ticket_data);
    ticket_data.due_date = moment(ticket_data.due_date, "MM-DD-YYYY").toDate(); 
    console.log(ticket_data.due_date);

The console.logs are returning:

{ ticket_name: 'Ticket Name',
  assigned_user: '5ec2b8b38b2508027f2f0c90',
  due_date: '21. 5. 2020',
  description: 'This is a test ticket' }
Invalid Date

I am unsure why I am getting back an invalid date, the formats seem to be correct. Is there a detail here I am missing? Thank you!

Upvotes: 1

Views: 2504

Answers (1)

joy08
joy08

Reputation: 9662

Try specifying format inside moment() , the format that you receive so that moment will parse it to a valid date.

let data = "21. 5. 2020";
let res = moment(data, "DD. M. YYYY"); // this will be valid moment date now
console.log(res.format("DD-MM-YYYY"));
<script src="https://momentjs.com/downloads/moment.js"></script>

Upvotes: 2

Related Questions