vue獲取時(shí)間戳轉(zhuǎn)換為日期格式。
方法一為轉(zhuǎn)載黃軼老師的format方法:出處(黃軼老師github https://github.com/ustbhuangyi);
// date.jsexport function formatDate (date, fmt) { if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); } let o = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds() }; for (let k in o) { if (new RegExp(`(${k})`).test(fmt)) { let str = o[k] + ''; fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str)); } } return fmt;}; function padLeftZero (str) { return ('00' + str).substr(str.length);};<!-- **.vue --><template> <!-- time時(shí)間戳 --> <div>{{time | formatDate}}</div> <!-- 輸出結(jié)果 --> <!-- <div>2016-07-23 21:52</div> --></template><script>import {formatDate} from './common/date.js';export default { filters: { formatDate(time) { var date = new Date(time); return formatDate(date, 'yyyy-MM-dd hh:mm'); } }}</script>方法二為自寫(在百度出的結(jié)果十個(gè)有九個(gè)是上述方法且在不想使用上述方法的情況下):
使用vue.filter
<!-- demo.vue --><template> <!-- time為時(shí)間戳 --> <div>{{time | formatDate}}</div> <!-- 結(jié)果為 2018-01-23 18:31:35 --></template><script type="text/ecmascript-6"> export default { data() { return { time: 1516703495241 }; }, filters: { formatDate: function (value) { let date = new Date(value); let y = date.getFullYear(); let MM = date.getMonth() + 1; MM = MM < 10 ? ('0' + MM) : MM; let d = date.getDate(); d = d < 10 ? ('0' + d) : d; let h = date.getHours(); h = h < 10 ? ('0' + h) : h; let m = date.getMinutes(); m = m < 10 ? ('0' + m) : m; let s = date.getSeconds(); s = s < 10 ? ('0' + s) : s; return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s; } } };</script><style lang="stylus" rel="stylesheet/stylus"> </style>以上所述是小編給大家介紹的vue獲取時(shí)間戳轉(zhuǎn)換為日期格式詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)錯(cuò)新站長(zhǎng)站網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選