一個簡單的 js 時間對象創建


JS中獲取時間很常見,湊湊熱鬧,也獲取一個時間對象試試

首先,先了解js的獲取時間函數如下:

var myDate = new Date();          //創建一個時間對象

myDate.getYear();                      // 獲取當前年份(2位)

myDate.getFullYear();                // 獲取當前完整的年份(4位,1970----???)

myDate.getMonth();                   // 獲取當前月份(0--11,   0 代表1月)

myDate.getDate();                      // 獲取當前是哪一日 (1----31)

myDate.getDay();                       // 獲取當前是哪一天,即星期幾(0---6 ,0代表星期天)

myDate.getTime();                      // 獲取當前時間的毫秒數(從1970.1.1開始計算)

myDate.getHours();                    // 獲取當前時間的小時數(0---23)

myDate.getMinutes();                  //獲取當前時間的分鍾數 (0---59)

myDate.getSeconds();                // 獲取當前時間的秒數 (0---59)

myDate.getMilliseconds();           // 獲取當前時間的毫秒數 (0---999)

myDate.toLocaleDateString();     // 獲取當前時間的日期

myDate.toLocaleTimeString();     // 獲取當前時間

myDate.toLocaleString();             //獲取當前日期與時間

 

創建一個時間如下:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Document</title>
 6   <style>
 7     .box{
 8       margin:200px auto;
 9       width:400px;
10     }
11     span,code{
12        display: inline-block;
13        font-size: 75px;
14     }
15   </style>
16   <script>
17       window.onload = function(){
18 
19         function OTime(){
20           this.aspan = document.querySelectorAll('.box span');
21         };
22         OTime.prototype.todouble = function( n ){
23           return n>10 ? '' + n : '0'+ n ;
24         };
25         OTime.prototype.getcurtime = function(){
26           var odate = new Date();
27           var OHour = odate.getHours();
28           var OMin = odate.getMinutes();
29           var OSec = odate.getSeconds();
30           return this.todouble( OHour ) + this.todouble( OMin ) + this.todouble( OSec ) ;
31         };
32         OTime.prototype.setcurTime = function(){
33           var str = this.getcurtime();
34           for(var i=0;i<this.aspan.length;i++){
35             this.aspan[i].innerHTML = str.charAt( i );
36           };
37         };
38         OTime.prototype.showtime = function(){
39           this.setcurTime();
40           var that = this ;
41           setInterval(function(){
42             that.setcurTime();
43           },1000);
44         };
45         var curtime = new OTime();
46         curtime.showtime();
47 
48       };
49   </script>
50 </head>
51 <body>
52   <div class="box">
53       <span>2</span>
54       <span>2</span>
55       <code>:</code>
56       <span>1</span>
57       <span>1</span>
58       <code>:</code>
59       <span>3</span>
60       <span>3</span>
61   </div>
62 </body>
63 </html>

 

運行結果:

 


免責聲明!

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



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