0
点赞
收藏
分享

微信扫一扫

JS yyyyMMddHHmmss转换yyyy-MM-dd HH:mm:ss

alonwang 2022-04-20 阅读 250

js 中时间yyyyMMddHHmmss 转化成时间格式yyyy-MM-dd HH:mm:ss

/**
 * 时间格式化
 * @param time yyyyMMddhhmmss
 * @returns {string}
 */
function dateTimeStr(time) {
    if (time === null || time ===''){
        return '';
    }
    let date_value=time.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, "$1-$2-$3 $4:$5:$6")
    return date_value;
}

js 时间格式化工具类
格式化参数fmt 例如: yyyy-MM-dd HH:mm:ss
需要格式化时间戳 time 例如 :1650372472

function dateFormat(fmt, time) {
    if (time === null || time ===''){
        return '';
    }
    let date = new Date(time)
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加,必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}

本人拙见仅供参考!

举报

相关推荐

0 条评论