1. 程式人生 > 其它 >js 時間戳與時間的相互轉換

js 時間戳與時間的相互轉換

時間戳轉換成 “yyyy-MM-dd hh:mm:ss”格式:

happenTimeFun(num){//時間戳資料處理

         let date = new Date(num);
        //時間戳為10位需*1000,時間戳為13位的話不需乘1000
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;//月補0
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;//天補0
    let h = date.getHours();
    h 
= h < 10 ? ('0' + h) : h;//小時補0 let m = date.getMinutes(); m = m < 10 ? ('0' + m) : m;//分鐘補0 let s = date.getSeconds(); s = s < 10 ? ('0' + s) : s;//秒補0 return y + '-' + MM + '-' + d + ' ' + h + ':' + m+ ':' + s; } happenTimeFun(1628648245);

“yyyy-MM-dd hh:mm:ss”轉換成時間戳:

timeProcessing(){
    let timeDate 
= "2020-08-11 11:08:48"; let Time = new Date(timeDate); console.log(Time)// (中國標準時間) let timestemp = Time.getTime(); console.log(timestemp) }