将指定格式的字符串解析为日期字符串

4年以前  |  阅读数:418 次  |  编程语言:JavaScript 
const dataPattern = (str, format = '-') => {
     if (!str) {
         return new Date()
     }
     const dateReg = new RegExp(`^(\\d{2})${format}(\\d{2})${format}(\\d{4})$`)
     const [, month, day, year] = dateReg.exec(str)
     return new Date(`${month}, ${day} ${year}`)
 }

 console.log(dataPattern('12-25-1995')) // Mon Dec 25 1995 00:00:00 GMT+0800 (中国标准时间)

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8