如何將時間格式化


 
        
 1 export function formatDate(date, fmt) {
 2   //獲取年份
 3   //y+  -->1個或者多個y
 4   //y*  -->0個或者多個y
 5   //y?  -->0個或者1個y
 6   if(/(y+)/.test(fmt)){
 7     // RegExp.$1是RegExp的一個屬性,指的是與正則表達式匹配的第一個字匹配(以括號為標志)字符串,一共有RegExp.$99個匹配項
 8     //replace() 替換    (date.getFullYear() + '') 將獲取到的年份(數字)拼接成字符串
 9     // substr() 截取  比如傳過來的是‘yyyy’  substr(4-4) 即截取0個 截取前2位
10     fmt = fmt.replace(RegExp.$1,(date.getFullYear() + '').substr(4-RegExp.$1.length));
11   }
12     let o = {
13       'M+': date.getMonth() + 1,
14       'd+': date.getDate(),
15       'h+': date.getHours(),
16       'm+': date.getMinutes(),
17       's+': date.getSeconds()
18     };
19   for (let k in o){
20     if(new RegExp(`(${k})`).test(fmt)){
21       let str = o[k] + '';
22       fmt = fmt.replace(RegExp.$1,(RegExp.$1.length === 1) ? str : padLeftZero(str));
23     }
24   }
25   return fmt
26 };
27 function padLeftZero(str) {
28   //會有4:4:4   padLeftZero(str) {} 將其轉化成04:04:04
29   return ('00' + str).substr(str.length) //截取
30 }

在所需要的文件中使用

<!--  過濾器   時間戳    -->
        <span class="data">{{commentInfo.created | showDate }}</span>

 

 1 import {formatDate} from "common/utils";
 2     export default {
 3         name: "DetailCommentInfo",
 4         props:{
 5             commentInfo:{
 6                 type:Object,
 7                 default(){
 8                     return {}
 9                 }
10             }
11         },
12         filters:{
13           showDate(value) {
14           //1.將時間戳轉成Date對象
15           const date = new Date(value*1000);
16           // 2.將date進行格式化
17           return formatDate(date,'yyyy-MM-dd') 18         }
19       }
20     }

效果圖:

 

 

 

 
       


免責聲明!

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



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