[JS] front-end date format conversion function



/**
 * 日期时间格式转化
 * @param date 时间
 * @param fmt 转化格式 yyyy-MM-dd hh:mm:ss 不传转成:yyyy-MM-dd
 * @returns 格式时间字符
 */
const formatDate = (date, fmt = 'yyyy-MM-dd') => {
    
    
    if (date === null) return;
    if (typeof (date) == 'string' || typeof (date) == 'number') date = new Date(date);
    if (/(y+)/.test(fmt)) {
    
    
        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 (const k in opt) {
    
    
            const ret = new RegExp('(' + k + ')').exec(fmt)
            if (ret) {
    
    
                if (/(y+)/.test(k)) {
    
    
                    fmt = fmt.replace(ret[1], opt[k].substring(4 - ret[1].length))
                } else {
    
    
                    fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
                };
            };
        };
    };
    return fmt;
};



For more date and time processing methods, please click here to view

Guess you like

Origin blog.csdn.net/weixin_44244230/article/details/132086822