js时间戳转换成指定格式的字符串

function formatDate(time, formatStr) {
    let date = new Date(time);
    let Y = date.getFullYear();
    let M = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
    let D = date.getDate() < 10 ? '0' + (date.getDate()) : data.getDate();
    let h = date.getHours();
    let m = date.getMinutes();
    let s = date.getSeconds();
    formatStr = formatStr || 'YYYY-MM-DD H:m:s';
    return formatStr.replace(/YYYY|MM|DD|H|m|s/ig, function (matches) {
        return ({
            YYYY: Y,
            MM: M,
            DD: D,
            H: h,
            m: m,
            s: s
        })[matches];
    });
}
//格式字符串可改,但是必须符合年:YYYY 月:DD 日:DD 小时:H 分:m 秒:s
console.log(formatDate(new Date().getTime(),'YYYY-MM-DD H:m:s'));

猜你喜欢

转载自blog.csdn.net/wangshang1320/article/details/86083311