js毫秒时间戳转时间格式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32081725/article/details/86100167
var timestampToTime = (timestamp,format) => {
    var date = new Date(timestamp);
    var Y = date.getFullYear();
    var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    format=format.indexOf('Y')>-1?format.replace('Y',Y):format;
    format=format.indexOf('M')>-1?format.replace('M',M):format;
    format=format.indexOf('D')>-1?format.replace('D',D):format;
    format=format.indexOf('H')>-1?format.replace('H',H):format;
    format=format.indexOf('m')>-1?format.replace('m',m):format;
    format=format.indexOf('s')>-1?format.replace('s',s):format;
    return format
};
console.log(timestampToTime(new Date().getTime(),'Y-M-D H:m:s'));
console.log(timestampToTime(new Date().getTime(),'Y-M-D'));

猜你喜欢

转载自blog.csdn.net/qq_32081725/article/details/86100167
今日推荐