时间格式化函数

辰漪
2021-11-24 / 0 评论 / 58 阅读 / 正在检测是否收录...
/*
*@params date {Date Object} 日期
*@params fmt {String} 格式化方式
*@params bool {Boolean} 是否返回周几
*/
function dateFormat(date, fmt, bool) {
    date = new Date(date)
    console.log(date.getMonth() + 1, "月")
    console.log(date.getFullYear(), "年")
    console.log(date.getDate(), "日")
    console.log(date.getHours(), "时")
    console.log(date.getMinutes(), "分")
    console.log(date.getSeconds(), "秒")
    console.log(date.getDay(), "星期")
    date = new Date(date)
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds(), //毫秒
    }
    let weekStr = "" // 星期几
    const weekList = [
        { text: "周日", index: 0 },
        { text: "周一", index: 1 },
        { text: "周二", index: 2 },
        { text: "周三", index: 3 },
        { text: "周四", index: 4 },
        { text: "周五", index: 5 },
        { text: "周六", index: 6 },
    ]
    weekList.forEach((item) => (item.index === date.getDay() ? (weekStr = item.text) : ""))
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
            )
        }
    }
    if (bool) fmt = fmt + " " + weekStr
    return fmt
}

console.log(dateFormat(+new Date(), "yyyy-MM-dd hh:mm:ss", 1))
2
选择打赏方式:
微信

评论 (0)

取消