前端开发 中经常遇到需要转换后端返回的时间数据,转为前端需要自己的格式,使用开源库moment.js可以快速帮助我们转换,因为这个库已经提供很多时间转换方法,我们可以拿来直接使用,这个库的官方地址: GitHub – moment/moment: Parse, validate, manipulate, and display dates in javascript.
安装
npm install moment --save
在main.js注册转换过滤器
//定义moment全局日期过滤器
import Moment from 'moment'
Vue.filter('convertTime', function (data, formatStr) {
return Moment(data).format(formatstr);
});
在页面使用过滤器
{{ 'xxx' | convertTime('yyyy—mm—dd') }}
其他
也可以不在main.js注册过滤器(Vue 3没有过滤器,Vue 2才有过滤器),直接在vue页面的 script 使用内置的方法
使用moment将时间戳和日期互转:
- 时间:var time = new Date(); // Tue Aug 28 2018 09:16:06 GMT+0800 (中国标准时间)
- 时间戳:var timestamp = Date.parse(time); // 1535419062000 (Date.parse() 默认不取毫秒,即后三位毫秒为0)
- moment转时间:moment(time).valueOf(); // 1535419062126
- moment转时间戳:moment(timestamp).format(); // 2018-08-28T09:17:42+08:00