JavaScript convert string to date time

社会主义新天地 提交于 2019-12-25 18:34:53

问题


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?


回答1:


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.




回答2:


The milliseconds are saved (31), but what comes after that is not saved, because javascript does not support it.




回答3:


You could use library like Moment JS, You can read more http://momentjs.com/docs/

var day = moment("2016-07-30 00:00:01.0310000");

console.log(day._d); // Sat Jul 30 2016 00:00:01 GMT+0100 (WAT)


来源:https://stackoverflow.com/questions/37776970/javascript-convert-string-to-date-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!