js時間戳轉時間格式

/** 
* @Description: 時間戳轉時間
* @Param: timestamp:時間戳,format:格式YMD hms
* @return: 時間
* @Author: 王晨陽
* @Date: 2019/6/13-12:55
*/
function diyTime(timestamp,format) {
    if(timestamp.length === 10) {
        timestamp = timestamp * 1000;
    }
    var date = new Date(timestamp);//時間戳爲10位需*1000,時間戳爲13位的話不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds();
    var arrayValue = [Y,M,D,h,m,s];
    var arrayKey = ['Y','M','D','h','m','s'];
    var result = "";
    for(var i=0;i<arrayKey.length;i++) {
        if(format.indexOf(arrayKey[i]) > -1) {
            result += arrayValue[i];
        }
    }
    console.log(result);
    return result===""?Y+M+D:result;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章