一般我将一段时间字符串如2002-12-11 12:00:00
转成 Date
对象,直接用下面这段代码就行了:
new Date('2002-12-11 12:00:00')
可是MDN上写了这么一段说明:
注意: 由于浏览器之间的差异与不一致性,强烈不推荐使用Date构造函数来解析日期字符串 (或使用与其等价的Date.parse)。对 RFC 2822 格式的日期仅有约定俗称的支持。 对 ISO 8601 格式的支持中,仅有日期的串 (例如 “1970-01-01”) 会被处理为 UTC 而不是本地时间,与其他格式的串的处理不同。
所以直接使用new Date() 方法转的话,在不同操作系统、不同浏览器,生成的结果肯会有所差异。
为了使其做到兼容,可以字符串分割成具体年月日、时分秒,使用以下方法生成:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
具体代码:
function dateParse(dateString) {
const dateReg = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?.?(\d+)?$/
const d = dateString.match(dateReg)
if (d) {
// 月份取得是整数值,从0开始计算,要-1
const m = d[2] - 1 || 0
const ms = (d[7] || '0').substring(0, 3)
return new Date(d[1], m, d[3]
|| 1, d[4] || 0, d[5] || 0, d[6] || 0, ms)
}
return Date()
}