实现了从日期字符串生成日期对象的功能
// 调用示例 console.log(strToDate('2021-11-04 12:05:05'))
// 调用示例 console.log(strToDate('2021-11-04 12:05:05', 'yyyy-MM-dd hh:mm:ss'))
// 调用示例 console.log(strToDate('20211104', 'yyyyMMdd'))
// 调用示例 console.log(strToDate('20211104120505', 'yyyyMMddhhmmss'))
function strToDate(str, pattern = 'yyyy-MM-dd hh:mm:ss') {
if (str && typeof str === 'string') {
var formatIndex = [
/[y]+/.exec(pattern),
/[M]+/.exec(pattern),
/[d]+/.exec(pattern),
/[h]+/.exec(pattern),
/[m]+/.exec(pattern),
/[s]+/.exec(pattern)
]
var datePart = [0, 1, 1, 0, 0, 0]
var isRun = true
formatIndex.forEach((conf, index) =>{
var s = conf ? str.substr(conf.index, conf[0].length) : ''
if (s && isRun) {
datePart[index] = parseInt(s)
} else {
isRun = false
}
});
datePart[1] -= 1
return new Date(...datePart)
} else {
return ''
}
}