用vue封装时间工具函数

封装工具

使用函数封装不使用过滤器是因为,过滤器本身也是个函数, 而且vue3废弃了过滤器, 所以不使用

1、utils/date.js

import moment from 'moment'
// 设置中文模式
moment.locale('zh-cn')

/**
 * .....多久之前
 * @param {*} 之前的时间
 * @returns 系统时间到之前指定时间的距离值
 */
// 把目标日期转成多久之前通用函数
const timeAgo = targetDate => {
  return moment(targetDate).fromNow()
}
export {
  timeAgo
}

 2、main.js

把timeAgo函数挂载到Vue的原型上,这样在任意vue文件都可以直接使用了

import { timeAgo } from './utils/date'
Vue.prototype.$timeAgo = timeAgo

3、往页面上铺数据时,使用这个函数,把原本的时间当做参数传回去,会返回自己需要的时间

 <span>{{ $timeAgo(obj.pubdate) }}</span>

将视频的时间格式转换为00:00:00样式 

 组件

function formatDuraton(time){
                if(time > -1){
                    var hour = Math.floor(time/3600);
                    var min = Math.floor(time/60) % 60;
                    var sec = time % 60;
                    if(hour < 10) {
                        time = '0'+ hour + ":";
                    } else {
                        time = hour + ":";
                    }
 
                    if(min < 10){
                        time += "0";
                    }
                    time += min + ":";
 
                    if(sec < 10){
                        time += "0";
                    }
                    time += sec;
                }
                return time;
            }

html+js

<video @canplay="getDuration" ref="video"></video>

。。。。。。

getDuration(res) {
          let s = this.$refs.video.duration; //获取视频的总时长
          console.log(s+'=========获取视频的总时长')
          console.log(res)
          console.log(formatDuraton(Math.floor(s)))
      },

将视频的时间格式转换为00:00样式 

export function formatDuraton(time){
  if(time > -1){
      var hour = Math.floor(time/3600);
      var min = Math.floor(time/60);
      var sec = time % 60;
      if(min < 10){
          time = "0"+min+":";
      }else{
        time = min + ":"
      }

      if(sec < 10){
          time += "0";
      }
      time += sec;
  }
  return time;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值