Search code examples
javascript

How to convert string to date object in javascript?


I have a date string like '2019-06-12 12:02:12 232',how to convert to date using Javascript?

Date date = Date.parse('2019-06-12 12:02:12 232').format('yyyy-MM-dd dd:HH:ss SSS');

I want to compare two date to calculate the minisecond in Javascript.Any suggestion?How could I tweak my date string?The date string was generate is server side using Java:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS");
String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);

This question does not contain minisecond,if no minisecond,Date.parse could solved the problem.My question is precise contain more detail operation of Javascript Date.


Solution

  • You can do it like that:

    const dateString = "2019-06-12 12:02:12 232"
    const [y,M,d,h,m,s] = dateString.split(/[- :]/);
    const 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");
    

    Moreover, you could check if a date is valid:

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