时间戳转换标准日期


/**

*formatTime参数

* 第一个参数:时间戳,(必填项)

* 第二个参数:日期间隔符,默认为 -,(选填)

* 第三个参数:时分秒间隔符,默认为 :,(选填)

* 第四个参数:是否携带时分秒,默认为 true,(选填)
*/

let time = formatTime(1579258960);

console.log(time);//2020-01-17 19:02:40


function formatTime(timestamp,separator='-',timeS=':',flag = true) {

    let str = '';
    let date = new Date(timestamp * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + separator;
    let M = autoChange(date.getMonth() + 1) + separator; //计算机的月份是从0开始滴,需要+1
    let D = autoChange(date.getDate());
    str = Y + M + D ;
    if(flag){
        let h = autoChange(date.getHours()) + timeS;
        let m = autoChange(date.getMinutes()) + timeS;
        let s = autoChange(date.getSeconds());
        let timeStr = h + m + s ;
        str += " ";
        str += timeStr;
    }
    return str;
}
function autoChange(num) {
    if (num < 10) {
        return "0" + num;
    } else {
        return num;
    }
}

原文地址:https://www.cnblogs.com/fanqiuzhuji/p/12192008.html