js字串轉時間戳
阿新 • • 發佈:2018-11-02
(1)把當前時間轉成時間戳
//把時間轉成時間戳
function timeTampToStr(){
// 當前時間戳
var timestamp = parseInt(new Date().getTime()/1000);
document.write(timestamp);
}
(2)當前時間換日期字串
//把當前時間轉成字串 function currentTimeChangeStr(){ //獲取當前時間 var now = new Date(); //獲取當前時間的年份 var yy = now.getFullYear(); //年 //獲取當前時間的月份 var mm = now.getMonth() + 1; //月 //獲取當前時間的日期 var dd = now.getDate(); //日 //獲取當前時間的小時 var hh = now.getHours(); //時 //獲取當前時間的分 var ii = now.getMinutes(); //分 //獲取當前時間的秒 var ss = now.getSeconds(); //秒 //把上述的時間轉成字串 var clock = yy + "-"; if(mm < 10) clock += "0"; clock += mm + "-"; if(dd < 10) clock += "0"; clock += dd + " "; if(hh < 10) clock += "0"; clock += hh + ":"; if (ii < 10) clock += '0'; clock += ii + ":"; if (ss < 10) clock += '0'; clock += ss; //獲取當前日期 document.write(clock); }
(3)日期字串轉時間戳
//日期字串轉成時間戳
//例如var date = '2015-03-05 17:59:00.0';
function dateStrChangeTimeTamp(dateStr){
dateStr = dateStr.substring(0,19);
dateStr = dateStr.replace(/-/g,'/');
var timeTamp = new Date(dateStr).getTime();
document.write(timesTamp);
}
(4)時間戳轉日期字串
//把時間戳轉成日期格式 //例如 timeTamp = '1425553097'; function formatTimeTamp(timeTamp){ var time = new Date(timeTamp*1000); var date = ((time.getFullYear()) + "-" + (time.getMonth() + 1) + "-" + (time.getDate()) + " " + (time.getHour()) + ":" + (time.getMinutes()) + ":" + (time.getSeconds()); ) document.write(date); }