题解 | #时间格式化输出#
时间格式化输出
http://www.nowcoder.com/practice/a789783e7c984f10a0bf649f6d4e2d59
function formatDate(date, fmt){
let dateObj = new Date(date)
let year = dateObj.getFullYear()
let month = dateObj.getMonth() + 1
let dat = dateObj.getDate()
let hours = dateObj.getHours()
let minutes = dateObj.getMinutes()
let sec = dateObj.getSeconds()
let day = dateObj.getDay()
fmt = fmt.replace(/(y+)/g,function(match,p1){
return String(year).replace(new RegExp(`^\\d{${4-p1.length}}`,'g'),'')
})
fmt = fmt.replace(/(M+)/g,function(match,p1){
return p1.length > 1 && month < 10 ? '0' + month : month
})
fmt = fmt.replace(/(d+)/g,function(match,p1){
return p1.length > 1 && dat < 10 ? '0' + dat : dat
})
fmt = fmt.replace(/(H+)/g,function(match,p1){
return p1.length > 1 && hours < 10 ? '0' + hours : hours
})
fmt = fmt.replace(/(h+)/g,function(match,p1){
if(hours > 12){
hours-= 12
}
return p1.length > 1 && hours < 10 ? '0' + hours : hours
})
fmt = fmt.replace(/(m+)/g,function(match,p1){
return p1.length > 1 && minutes < 10 ? '0' + minutes : minutes
})
fmt = fmt.replace(/(s+)/g,function(match,p1){
return p1.length > 1 && sec < 10 ? '0' + sec : sec
})
fmt = fmt.replace(/(w?)/g,function(match,p1){
return p1 ? ['日', '一', '二', '三', '四', '五', '六'][day]:''
})
return fmt
} 
基恩士成长空间 433人发布