時間戳的轉換
阿新 • • 發佈:2020-07-15
(一)時間戳轉為當前時間
var a = 1594810549 console.log(timestampToTime(a)) //2020-07-15->18:55:49 function timestampToTime(timestamp){ var date = new Date(timestamp * 1000);//時間戳為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(); return Y+M+D+ '->' +h+m+s; }
(二)當前時間轉為時間戳
var date = new Date('2020-7-15 18:55:49:123');//後三位為毫秒 var time1 = date.getTime(); var time2 = date.valueOf(); var time3 = Date.parse(date); console.log(time1);//1594810549123 console.log(time2);//1594810549123 console.log(time3);//1594810549000
附帶一個for in 小迴圈
var b = [1,2,3,4] for(let index in b){ console.log(b[index]) }