JS 实时获取并显示当前日期和时间

 1 function ShowTime() {
 2     let t = window.setInterval(function GetTime() {
 3         var time1 = new Date();
 4         var year = time1.getFullYear();
 5         var month = time1.getMonth() + 1;
 6         if (month < 10) {
 7             month = "0" + month;
 8         } else { }
 9         var date = time1.getDate();
10         if (date < 10) {
11             date = "0" + date;
12         } else { }
13         var hour = time1.getHours();
14         if (hour < 10) {
15             hour = "0" + hour;
16         } else { }
17         var minute = time1.getMinutes();
18         if (minute < 10) {
19             minute = "0" + minute;
20         } else { }
21         var second = time1.getSeconds();
22         if (second < 10) {
23             second = "0" + second;
24         } else { }
25         var time = year + '年' + month + '月' + date + "日  " + hour + ":" + minute + ":" + second;
26         var timeid = document.getElementById("time"); //获取想要显示时间的标签id
27         timeid.innerHTML = time;//将拼接好的字符串显示在标签内
28     }, 1000);
29     //设置暂定 window.clearInterval(t);
30 }

当页面加载时调用显示方法

<body onload="ShowTime()">

显示效果:

 

posted @ 2020-07-16 16:14  幸运(● ̄(エ) ̄●)  阅读(892)  评论(0编辑  收藏  举报
Document