js中時間的獲取、定時器的使用


 

 1   <style>
 2  .time {
 3  background-color: antiquewhite;
 4  width: 150px;
 5  height: 50px;
 6  text-align: center;
 7  font-size: 20px;
 8       }
 9   </style>
10   <script type="text/javascript">
11         function getTime() { 12             var now = new Date(); 13             //獲取相對於1900的時間差,比如2019年,獲取的數字是 119
14             var year = now.getYear(); 15             //獲取完整的年份
16  year = now.getFullYear(); 17             //范圍0~11, 跟中國的月份相差1
18             var month = now.getMonth()+1; 19             //getDate表示獲取當前時間對應的月份中的天數
20             var days = now.getDate(); 21             //表示獲取星期數 ,西方國家的星期數是 0~6,0代表的是周日,其他的分別是周一到周六
22             var dayOfWeek = now.getDay() ; 23             //獲取當前小時
24             var hour = now.getHours(); 25             //獲取當前分鍾
26             var minutes = now.getMinutes(); 27             //獲取當前秒
28             var seconds = now.getSeconds(); 29             //拼接時間格式, 年-月-日 時:分:秒
30             var time1 = year+"-"+month+"-"+days+"  "+hour+":"+minutes+":"+seconds; 31             
32  document.getElementById("time").innerText = time1; 33  } 34         //定義將使用的定時器
35         var timeout = setInterval(); 36         
37         //打開定時器
38         function startInterval() {
39 timeout = setInterval("getTime()",1000); 40 }              //setInterval(調用方法,刷新間隔) 41 42 //清空定時器,即停止定時器 43 function closeInterval() { 44 clearInterval(timeout); 45 }         46 47 </script> 48 </head> 49 50 <body background="../../img/imgBg/blueBg2.jpg"> 51 52 <div id="time" class="time">顯示時間</div><br /> 53 54 <input type="button" name="closeBtn" value="停止" onclick="closeInterval()" /> 55 56 <input type="button" name="startBtn" value="開始" onclick="startInterval()" /> 57 58 </body> 59

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM