JS 读取 excel 数据后的时间格式转换

1,056 阅读1分钟

一、将 excel 日期数值转换为正常日期格式

  • 使用 xlsx.full.min.js 获取 excel 的日期数据为:42358

  • 拿到的整数值是日期距离 1900年1月1日 的天数,这时需要写一个函数转换:

    function formatDate (numb, format) {
      let time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      let year = time.getFullYear() + ''
      let month = time.getMonth() + 1 + ''
      let date = time.getDate() + ''
      if(format && format.length === 1) {
        return year + format + month + format + date
      }
      return year+(month < 10 ? '0' + month : month)+(date < 10 ? '0' + date : date)
    }
    
    console.log(formatDate(42358, '/'))
    
    输出:`2015/12/20`
    

二、将正常日期格式转换为 Excel 日期数值

  • 计算 1900-01-01 - 2015-12-20 间隔多少天

    function fun () {
        let startTime = new Date('1900-01-01'); // 开始时间
        let endTime = new Date('2015-12-20'); // 结束时间
        // 间隔天数,为什么需要 +2,这里计算出来的只是中间的差值天数,加开头结尾的各一天就是2天,所以 +2
        return Math.floor((endTime - startTime) / 1000 / 60 / 60 / 24) + 2
    }
    
    console.log(fun())
    
    输出:`42358`