小程序中时间计算(时、分、秒)

直接把代码拿到uniapp上运行
控制台打印
注意:在操作的时候可能会出现(无效的时间)
由于是ios不支持横杠(-) 2022-10-23 13:00:00,把(-)换成(/)就ok了

<template>
  <view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        time: '',
      };
    },
    onLoad(options) {
      this.time = this.getTime()
      console.log(this.time)
      this.getDateDiff(this.time)
    },
    methods: {
      //获取当前时间
      getTime: function() {
        var date = new Date(),
          year = date.getFullYear(),
          month = date.getMonth() + 1,
          day = date.getDate(),
          hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
          minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
          second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        month >= 1 && month <= 9 ? (month = "0" + month) : "";
        day >= 0 && day <= 9 ? (day = "0" + day) : "";
        var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
        return timer;
      },

      getDateDiff(data) {
        console.log('当前时间:'+data)
        var time = this.getDays(new Date('2022-10-23 13:00:00'), new Date('2022-10-23 17:24:06 '));
      },
      getDays: function(date1, date2) {
        console.log('date2:'+date2.getTime())
        console.log('date1:'+date1.getTime())
        console.log('时间差:'+(date2.getTime() - date1.getTime()))
        //每一天的毫秒数
        const dateTime = 1000 * 60 * 60 * 24;
        //计算出两个日期的天数差
        const dateDiff = Math.floor(((date2.getTime() - date1.getTime())));
        console.log('dateDiff:'+dateDiff)
        var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000))
        var leave1 = dateDiff % (24 * 3600 * 1000)
        console.log('leave1:'+leave1)
        var hours = Math.floor(leave1 / (3600 * 1000))
        console.log('相差小时数:' + hours)
        //分钟数
        var leave2 = leave1 % (3600 *1000)
        var minutes = Math. floor(leave2 / (60 *1000))
        console. log('相差分钟数:'+ minutes )
        //秒
        var leave3 = leave2 % (60 *1000)
        var seconds = Math.round(leave3 / 1000)
        console. log('相差秒数:'+seconds)
        return dayDiff
      },
    }
  }
</script>

<style lang="scss">
</style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值