且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript将字符串转换为日期时间

更新时间:2023-02-03 15:48:38

您必须自己解析该字符串(这很简单,唯一棘手的位是在毫秒值上尾随零),然后使用 Date(年,月,日,小时,分钟,秒,毫秒)构造函数。或使用库和格式字符串。

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.

下面是一个示例:

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());
}

在正则表达式中, \d 表示数字, {x} 表示重复x次。

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

!部分? null:新的Date(...)位是这样,如果字符串与格式不匹配,我们将得到 null 而不是错误

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