user316114 user316114 - 5 months ago 189
Javascript Question

JavaScript convert string to date time

I have a string that contains a datetime in the following format

2016-07-30 00:00:01.0310000


I need to convert this to a datetime object in JavaScript retaining the sub-seconds.

If I use

var d = new Date('2016-07-30 00:00:01.0310000');


Everything after 01 is dropped, how can I efficiently achieve this?

Answer

You'll have to parse the string yourself (which is quite simple, the only tricky bit is trailing zeros on the milliseconds value) and build the date using the Date(years, months, days, hours, minutes, seconds, milliseconds) constructor. Or use a library and a format string.

Here's an example:

var str = "2016-07-30 00:00:01.0310000";
var parts = /^\s*(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d+)\s*$/.exec(str);
var dt = !parts ? null : new Date(
    +parts[1],                   // Years
    +parts[2] - 1,               // Months (note we start with 0)
    +parts[3],                   // Days
    +parts[4],                   // Hours
    +parts[5],                   // Minutes
    +parts[6],                   // Seconds
    +parts[7].replace(/0+$/, '') // Milliseconds, dropping trailing 0's
);
if (dt.toISOString) {
  console.log(dt.toISOString());
} else {
  console.log("date", dt.toString());
  console.log("milliseconds", dt.getMilliseconds());
}

In the regex, \d means "a digit" and {x} means "repeated x times".

The !parts ? null : new Date(...) bit is so that if the string doesn't match the format, we get null rather than an error.

Comments