1. 程式人生 > >vue項目裏的日期格式化

vue項目裏的日期格式化

return 引入 atd template png orm padleft pad 9.png

在項目中,我們經常需要把後臺傳回的日期進行格式化,可以在common裏定義一個公共的js

技術分享圖片

技術分享圖片
 1 export function formatDate (date, fmt) {
 2   if (/(y+)/.test(fmt)) {
 3     fmt = fmt.replace(RegExp.$1, (date.getFullYear() + ‘‘).substr(4 - RegExp.$1.length))
 4   }
 5   let o = {
 6     ‘M+‘: date.getMonth() + 1,
 7     ‘d+‘: date.getDate(),
 8     ‘h+‘: date.getHours(),
 9     ‘m+‘: date.getMinutes(),
10     ‘s+‘: date.getSeconds()
11   }
12   for (let k in o) {
13     if (new RegExp(`(${k})`).test(fmt)) {
14       let str = o[k] + ‘‘
15       fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
16     }
17   }
18   return fmt
19 }
20 
21 function padLeftZero (str) {
22   return (‘00‘ + str).substr(str.length)
23 }
技術分享圖片

vue文件引入

技術分享圖片

js文件用的是export, vue文件引入的時候需要加{}

技術分享圖片

箭頭對應的就是上面{}裏面的

template中這樣使用::

技術分享圖片

vue項目裏的日期格式化