格式化时间方法(封装)

本文介绍了如何在Vue项目中引入dayjs库,用于时间的格式化,并展示了多个自定义过滤器的实现,如时间转换为年月日、小时分钟等不同格式。此外,还演示了在main.js中注册过滤器并在模板中使用的步骤。

第一步:引入第三方插件dayjs

npm install dayjs --save

 第二步:写好格式化时间的方法

import dayjs from 'dayjs'

export default {
  bodyNUllShow(value) {
    if (value === 0 || value === '0' || value === '' || value === null) {
      return '一'
    } else {
      return value
    }
  },
  timeToYMDHms(time) {
    if (!time && typeof time !== 'string') return ''
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
  },
  timeToYMDHm(time) {
    if (!time && typeof time !== 'string') return ''
    return dayjs(time).format('YYYY-MM-DD HH:mm')
  },
  timeToYMD(time) {
    if (!time && typeof time !== 'string') return ''
    return dayjs(time).format('YYYY年MM月DD日')
  },
  timeToYMD2(time) {
    if (!time && typeof time !== 'string') return ''
    return dayjs(time).format('YYYY-MM-DD')
  },
  timeToMDHm(time) {
    if (!time && typeof time !== 'string') return ''
    return dayjs(time).format('MM-DD HH:mm')
  },
  timeToFormat(time, format) {
    if (!time && typeof time !== 'string') return ''
    return dayjs(time).format(format)
  },
  timeToHMS(time) {
    if (!time && typeof time !== 'string') {
      time = 0
    }
    time = Math.floor(time / 1000)

    var day = Math.floor(time / (24 * 3600)) // Math.floor()向下取整
    var hour = Math.floor((time - day * 24 * 3600) / 3600)
    var minute = Math.floor((time - day * 24 * 3600 - hour * 3600) / 60)
    var second = time - day * 24 * 3600 - hour * 3600 - minute * 60

    return hour + '时' + minute + '分' + second + '秒'
  },
  wordLimit(word, num) {
    let newWord = ''
    if (word.length > num) {
      newWord = word.substring(0, num) + '...'
    } else {
      newWord = word
    }
    return newWord
  }
}

第三步,在main.js中引用,这里用到的是vue中的过滤器

import filters from './filters'

// register filters(过滤器)
Object.keys(filters).forEach(key => Vue.filter(key, filters[key]))

第四步,在页面中使用过滤器

<template>
    <div class="mt20">{{ time | timeToYMDHms }}</div>
</template>

<script>
export default {
  data() {
    return {
      time: null
    }
  },
  created() {
    this.timeStart()
  },
  methods: {
    timeStart() {
      // 设置定时器
      this.timer = setInterval(() => {
        this.time = Date.parse(new Date())
      }, 1000)
    }
  },
}
</script>
<style>
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值