js獲取當前時間以及30s後的時間
阿新 • • 發佈:2018-11-09
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="Date"></div> <div id="30Date"></div> </body> </html> <script type="text/javascript"> window.onload = function() { setInterval(function() { var date = new Date(); var year = date.getFullYear(); //獲取當前年份 var mon = date.getMonth() + 1; //獲取當前月份 var da = date.getDate(); //獲取當前日 var h = date.getHours(); //獲取小時 var m = date.getMinutes(); //獲取分鐘 var s = date.getSeconds(); //獲取秒 var ts=s+30; //將時間格式轉化為時間戳 var oDate1 = new Date(year,mon,da,h ,m,s); //當前的時間 var oDate2 = new Date(year,mon,da,h,m,ts); //30s之後的時間 var nTime = oDate2.getTime() - oDate1.getTime(); //之間的時間戳 var nn=timestampToTime(parseInt(nTime+new Date().getTime()));//之間的時間戳+當前的時間 var d = document.getElementById('Date'); var threed= document.getElementById('30Date'); d.innerHTML = '當前時間:' + year + '年' + mon + '月' + da + '日 ' + h + ':' + m + ':' + s; threed.innerHTML = '當前30s之後的時間:' +nn; tt(); }, 30) function timestampToTime(nTime) { var date = new Date(nTime);//時間戳為10位需*1000,時間戳為13位的話不需乘1000 var Y = date.getFullYear() + '-'; var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; var D = date.getDate() + ' '; var h = date.getHours() + ':'; var m = date.getMinutes() + ':'; var s = date.getSeconds(); return Y+M+D+h+m+s; } function tt(){ console.log('fff'); } } </script>