vue使用Moment插件格式化时间

使用npm命令安装moment

npm install moment --save

在main.js文件里引用moment

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Moment from 'moment'

// 定义全局时间戳过滤器
Vue.filter('formatDate', function(value) {
  return Moment(value).format('YYYY-MM-DD HH:mm:ss')
})

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

在组件里使用

<div class="time">{{item.rateTime | formatDate}}</div>

常用的一些日期格式化方法

  1. 日期格式化
    moment().format('MMMM Do YYYY, h:mm:ss a'); // 四月 16日 2019, 12:24:48 中午
    moment().format('dddd');                    // 星期二
    moment().format("MMM Do YY");               // 4月 16日 19
    moment().format('YYYY [escaped] YYYY');     // 2019 escaped 2019
    moment().format();                          // 2019-04-16T12:24:48+08:00
    

  2. 相对时间
    moment("20111031", "YYYYMMDD").fromNow(); // 7 年前
    moment("20120620", "YYYYMMDD").fromNow(); // 7 年前
    moment().startOf('day').fromNow();        // 12 小时前
    moment().endOf('day').fromNow();          // 12 小时内
    moment().startOf('hour').fromNow();       // 28 分钟前
    

  3. 日历时间
    moment().subtract(10, 'days').calendar(); // 2019年4月6日
    moment().subtract(6, 'days').calendar();  // 上周三中午12点28
    moment().subtract(3, 'days').calendar();  // 上周六中午12点28
    moment().subtract(1, 'days').calendar();  // 昨天中午12点28分
    moment().calendar();                      // 今天中午12点28分
    moment().add(1, 'days').calendar();       // 明天中午12点28分
    moment().add(3, 'days').calendar();       // 本周五中午12点28
    moment().add(10, 'days').calendar();      // 2019年4月26日
    

  4. 多语言支持
    moment().format('L');    // 2019-04-16
    moment().format('l');    // 2019-04-16
    moment().format('LL');   // 2019年4月16日
    moment().format('ll');   // 2019年4月16日
    moment().format('LLL');  // 2019年4月16日中午12点28分
    moment().format('lll');  // 2019年4月16日中午12点28分
    moment().format('LLLL'); // 2019年4月16日星期二中午12点28分
    moment().format('llll'); // 2019年4月16日星期二中午12点28分
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值