<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>获取当前时间</title> </head> <body> <div class="kkk"> <p class="count" style="font-size: 50px;color: red;font-weight: 700;"></p> </div> <script type="text/javascript"> /** *获取当前时间 *format=1精确到天 *format=2精确到分 */ //处理时间 function addZero(i) { return i < 10 ? "0" + i : i + ""; } function getCurrentDate(format) { var now = new Date(); var year = now.getFullYear(); //得到年份 var month = now.getMonth() + 1;//得到月份 var date = now.getDate();//得到日期 var day = now.getDay();//得到周几 var hour = now.getHours();//得到小时 var minu = now.getMinutes();//得到分钟 var sec = now.getSeconds();//得到秒 month = addZero(month) date = addZero(date) hour = addZero(hour) minu = addZero(minu) sec = addZero(sec) var time = ""; //精确到天 if (format == 1) { time = '当前时间为:' + year + "-" + month + "-" + date; document.querySelector(".count").innerHTML = time; } //精确到分 else if (format == 2) { time = '当前时间为:' + year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec; document.querySelector(".count").innerHTML = time; } } getCurrentDate(2); </script> </body> <style> .kkk { 100%; height: 100vh; display: flex; justify-content: center; align-items: center; } </style> </html>