vue實時顯示當前時間且轉化為“yyyy-MM-dd hh:mm:ss”格式筆記


 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>vue實時顯示當前時間顯示</title>
 6     <link rel="stylesheet" href="../css/reset.css">
 7     <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
 8     <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
 9 </head>
10 <body >
11 <div id="app">當前實時時間:{{dateFormat(date)}}</div>
12 <script>
13     var vm=new Vue({
14         el:"#app",
15         data:{
16             date:new Date()
17         },
18         mounted () {
19             var _this = this; //聲明一個變量指向vue實例this,保證作用域一致
20             this.timer = setInterval(function() {
21                 _this.date = new Date();//修改數據date
22             }, 1000);
23         },
24         beforeDestroy () {
25             if(this.timer) {
26                 clearInterval(this.timer);//在vue實例銷毀錢,清除我們的定時器
27             }
28         },
29         methods:{
30             //時間格式化函數,此處僅針對yyyy-MM-dd hh:mm:ss 的格式進行格式化
31             dateFormat(time) {
32                 var date=new Date(time);
33                 var year=date.getFullYear();
34                 /* 在日期格式中,月份是從0開始的,因此要加0
35                  * 使用三元表達式在小於10的前面加0,以達到格式統一  如 09:11:05
36                  * */
37                 var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
38                 var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
39                 var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
40                 var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
41                 var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
42                 // 拼接
43                 return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
44             }
45         }
46     })
47 </script>
48 </body>
49 </html>

 


免責聲明!

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



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