题解 | #时间格式化输出#

时间格式化输出

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
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-11 13:34
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务