js计算日期差;js计算天数差

场景:首先要注意两种情况
1.只是计算年月日的天数差,例如2022-10-10 12:00:00与 2022-10-11 00:00:00 相差1天
2.计算包含时分秒的天数差,例如2022-10-10 12:00:00与 2022-10-11 00:00:00 相差0天
3.注意safari浏览器 将时分秒的转化为时间戳,需要使用new Date(‘2020-10-10 10:10:10’.replace(/-/g, ‘/’)).getTime()方法,否则转换会失败: ios中 safari浏览器,js时间操作getTime(),getFullYear()等返回显示NaN的解决办法

以下代码可直接复制:

<template>
  <div>
    <el-button @click="getDiffDay(date1,date2)">计算时间差值(看控制台)</el-button>
  </div>
</template>

<script>
export default {
    
    
  data () {
    
    
    return {
    
    
      date1: '2022-10-10',
      date2: '2022-10-12 00:00:00', // 可以修改成2022-10-12   带时分秒和不带时分秒的试试
    }
  },
  created () {
    
    

  },
  methods: {
    
    
    getDiffDay (date_1, date_2) {
    
    
      // // 计算两个日期之间的差值(这里将时分秒给截取掉  因为有时分秒时候 谷歌浏览器计算相差天数会少一天 而safari浏览器却没法将时分秒的转化为时间戳 会得到NaN 所以截取掉时分秒)

      // 具体是否截取时分秒 看你的需求是算日期之间差值还是毫米之间差值 2022-10-10 12:00:00与 2022-10-11 00:00:00

      // 情景1:截取后面的时分秒 计算两个日期之间的天数差值
      console.log('日期=====', date_1, date_2,)
      if (date_1 && date_1.indexOf(' ') >= 0) {
    
    
        date_1 = date_1.split(' ')[0]
      }
      if (date_2 && date_2.indexOf(' ') >= 0) {
    
    
        date_2 = date_2.split(' ')[0]
      }
      // 计算两个日期之间的天数差值
      let totalDays, diffDate
      let myDate_1 = Date.parse(date_1)
      let myDate_2 = Date.parse(date_2)
      // 将两个日期都转换为毫秒格式,然后做差
      diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值

      totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
      console.log('日期差值', totalDays)

      return totalDays    // 相差的天数




      // // 情景2:保留时分秒 计算毫米级的天数差值 例如 2022-10-10 12:00:00与 2022-10-11 00:00:00
      // console.log('日期=====', date_1, date_2,) 
      // let totalDays, diffDate
      // let myDate_1 = new Date(date_1.replace(/-/g, '/')).getTime()  // 解决safari浏览器 不能将时分秒的转化为时间戳 问题
      // let myDate_2 = new Date(date_2.replace(/-/g, '/')).getTime()  // 解决safari浏览器 不能将时分秒的转化为时间戳 问题
      // // 将两个日期都转换为毫秒格式,然后做差
      // diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值

      // totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
      // console.log('日期差值', totalDays)

      // return totalDays    // 相差的天数
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .el-input__inner {
    
    
  color: var(--inputColor); //使用css变量 注意变量前需要加 --
}
</style>

猜你喜欢

转载自blog.csdn.net/i_am_a_div/article/details/127979451