Vue中利用moment.js(时间格式化插件)做一个倒计时组件

moment.js 文档:https://momentjs.com/docs/#/-project-status/

1、使用npm安装moment

npm install moment --save

2、main.js中

import moment from 'moment'

Vue.config.productionTip = false// 导入文件
Vue.prototype.$moment = moment// 赋值使用
moment.locale('zh-cn')// 需要汉化

3、所应用的.vue页面

<template>
  <div>
    <div>输入格式为:YYYY-MM-DD HH:MM:SS</div><br/>
    <div>例如:2022-07-21 16:00:00</div><br/>
    <input class="input" v-model="dataValue" placeholder="请输入日期" />
    <button class="btn" @click="computeAction">计算</button>
    <div>倒计时:{{time}}</div>
  </div>
</template>

<script>
export default {
  name: 'index',
  data () {
    return {
      dataValue: '',
      time: ''
    }
  },
  mounted () {
  },
  methods: {
    computeAction () {
    /* 正则表达式
       1、匹配日期格式:yyyy-MM-dd 
	    /^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))$/
  	   2、匹配日期格式: yyyy-MM-dd HH:mm:ss
		/^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))\\s+([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/
    */
  
      let startT = this.$moment(new Date())// 获取当前时间
      let endT = this.$moment(new Date(this.dataValue))// 获取输入时间
      let diffT = endT.diff(startT)// 时间差
      let time = `${this.$moment.duration(diffT).years()}${this.$moment.duration(diffT).months()}${this.$moment.duration(diffT).days()}${this.$moment.duration(diffT).hours()}${this.$moment.duration(diffT).minutes()}${this.$moment.duration(diffT).seconds()}`// 格式化为需要的格式 YYYY-MM-DD HH:MM:SS
      this.time = time
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.input {
  width: 300px;
  padding: 10px;
  border: 0;
  outline: 0;
  -webkit-appearance: none;
  background-color: transparent;
  font-family: PingFangSC-Medium;
  font-weight: 500;
  font-size: 20px;
  color: rgba(0, 0, 0, 0.90);
  letter-spacing: 0;
  line-height: 20px;
  caret-color: #0DC060;
  border-radius: 4px;
  background: #F5F5F5;
  border: 1px solid rgba(0, 0, 0, 0);
  box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0);
  margin: 0 10px;
}

.btn {
  display: block;
  width: 160px;
  height: 48px;
  line-height: 48px;
  border-radius: 6px;
  font-size: 16px;
  background-color: #0dc060;
  color: #fff;
  border: 0;
  margin: 20px auto;
}
</style>

4、效果图:在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值