标准日期对象的方法:
一般使用toLocaleDataString或者toLocaleString而不用toString。
小时钟案例:
<html> <head> <meta charset="utf-8"> <style> #clockbox{ padding: 15px 0; line-height: 50px; color: aqua; } </style> </head> <body> <div id="clockbox"> </div> </body> <script> let clockbox = document.querySelector("#clockbox"); //进行补零 function addZero(val){ val = Number(val); return val<10?'0'+val:val; } //转换成所需格式 function queryData(){ let time = new Date(),//获取当前日期 year = time.getFullYear(), month = time.getMonth()+1,//0-11 day = time.getDate(), week = time.getDay(),//0-6 hours = time.getHours(), minutes = time.getMinutes(), seconds = time.getSeconds(); //进行字符串拼接 let weekary = ['日','一','二','三','四','五','六']; let result = `${year}年${addZero(month)}月${addZero(day)}日`; result += `星期${weekary[week]} ${addZero(hours)}时${addZero(minutes)}分${addZero(seconds)}秒`; clockbox.innerHTML = result; } //每隔一秒执行一次 setInterval(queryData,1000); </script> </html>