封装一个时间方法

function format(date, fmt = 'yyyy-MM-dd hh:mm:ss')
{
    if (typeof date === 'number') {
        // eslint-disable-next-line no-param-reassign
        date = new Date(date);
    } else if (typeof date === 'string') {
        // eslint-disable-next-line no-param-reassign
        date = new Date(Number(date));
    }
    const 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()
    };
    // eslint-disable-next-line no-param-reassign
    if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (String(date.getFullYear())).substr(4 - RegExp.$1.length)) }
    for (const k in o) {
        // eslint-disable-next-line no-param-reassign
        if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr((String(o[k])).length))) }
    }
    return fmt;
}

使用方法:

format(stbale.createTime, 'yyyy/MM/dd hh:mm:ss');
原文地址:https://www.cnblogs.com/yang656/p/11730486.html