vue獲取時間戳轉換為日期格式。
方法一為轉載黃軼老師的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時間戳 --> <div>{{time | formatDate}}</div> <!-- 輸出結果 --> <!-- <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>方法二為自寫(在百度出的結果十個有九個是上述方法且在不想使用上述方法的情況下):
使用vue.filter
<!-- demo.vue --><template> <!-- time為時間戳 --> <div>{{time | formatDate}}</div> <!-- 結果為 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獲取時間戳轉換為日期格式詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答