封装函数,实例化时间戳,再赋值到页面中:
-
<!DOCTYPE html> <html lang="ch-zn"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p></p> <script> let p = document.querySelector('p'); // 加载就获取 let time = new Date(); p.innerHTML = colock(time); function colock(date) { let y = date.getFullYear() let month = date.getMonth() + 1; let d = date.getDate(); let ymd = `${y}-${month}-${d}` let week = date.getDay(); // 转换获取到的星期值 let obj = { 0: '星期日', 1: '星期一', 2: '星期二', 3: '星期三', 4: '星期四', 5: '星期五', 6: '星期六', } for(let key in obj){ if(week==key){ week=obj[key]; } } let h = date.getHours(); let m = date.getMinutes(); let s = date.getSeconds(); let hms = `${h}:${m}:${s}${' '}${week}` return (ymd + ' ' + hms); } // 三元给个位数的添加0 function zero(n) { return n < 10 ? '0' + n : n; }; // 定时器获取最新时间 var t = setInterval(function () { let time = new Date(); p.innerHTML = colock(time); }, 1000) </script> </body> </html>