How to convert string to date object in javascript? [duplicate]

You can do it like that:

let date_string = "2019-06-12 12:02:12 232"
let [y,M,d,h,m,s] = date_string.split(/[- :]/);
let yourDate =  new Date(y,parseInt(M)-1,d,h,parseInt(m),s);
console.log(`yourDate ${yourDate}`);

In addition, avoid using Date.parse() method.

UPDATE:

By using the above approach, you will avoid some strange bugs as described in the above link. However, it is possible to use a great library Moment.js:

moment("12-25-1995", "MM-DD-YYYY");

In addition, you could check if a date is valid:

moment("whether this date is valid").isValid(); // OUTPUT: false

Leave a Comment