【JS】获取当前时间戳以及计算时间差 +【AntDesign】时间日期控件计算差值踩坑

【时间Date转时间戳】

const d = Date.now()
// 结果:1625573962353
const d1 = (new Date()).valueOf();
// 结果:1625573962353,通过valueOf()函数返回指定对象的原始值获得准确的时间戳值;

const d2 = new Date().getTime();
// 结果:1625573962353,通过原型方法直接获得当前时间的毫秒值;

const d3 = Number(new Date()) ;
//结果:1625573962353,将时间转化为一个number类型的数值,即时间戳;

【时间戳转时间Date】

let date = new Date(1625573962353);
// Tue Jul 06 2021 20:19:22 GMT+0800 (中国标准时间)

【改造前:计算时间差示例】

watch: {
  startTime (newValue, oldValue) {
      const d = Date.now()
      if (newValue > d) {
        this.$message.warning('选中时间不得大于当前时间')
        this.startTime = undefined // newValue  = undefined似乎不管用
      }
      const diff = (this.endTime - newValue) / 1000 / 60
      if (diff < 0) {
        this.$message.warning('结束时间需大于开始时间')
        this.startTime = undefined
      } else if (diff > 30) {
        this.$message.warning('时间差需小于30分钟')
        this.startTime = undefined
      }
    }
}

由于业务需要时间控件[时分秒] 和日期控件[年月日] 要分开使用,且不可选择将来的时间

但是使用AntDesign时间日期控件时,日期控件 和 时间控件 打印出来的数值均带有年月日时间,所以不能直接用于比较大小
在这里插入图片描述

【改造后:计算时间差示例】

watch: {
  startTime (newValue, oldValue) {
      const d = Date.now()
      const nowDate = moment().format('yyyy-MM-DD')
      if (newValue > d && this.dateValue >= nowDate) {
        this.$message.warning('选中时间不得大于当前时间')
        this.startTime = undefined
      }
      const diff = (this.endTime - newValue) / 1000 / 60
      if (diff < 0) {
        this.$message.warning('结束时间需大于开始时间')
        this.startTime = undefined
      } else if (diff > 30) {
        this.$message.warning('时间差需小于30分钟')
        this.startTime = undefined
      }
    }
}

【自己动手获取年月日】

// 返回当前日期yyyy-MM-DD格式
    nowDate () {
      var date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      var nowDate = year + '-' + month + '-' + day
    },

【时间格式化】

// moment为常用时间处理插件,官网:http://momentjs.cn/
const nowDate = moment().format('yyyy-MM-DD') // 当前时间格式化
const fdate = moment(date).format('yyyy-MM-DD') // 指定date格式化
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值