关于导入excel时js转换时间的正确方式

目录

  • 一、基础
  • 二、问题描述
  • 三、解决思路
  • 附:js读取excel中日期格式转换问题
  • 总结

一、基础 1、excel的日期是以1900-1-0开始计算的,既1900-1-1就是1天;
2、js的Date是以 1970-1-1 08:00:00 开始的;
excel时间换算如下:
关于导入excel时js转换时间的正确方式
文章图片

点击常规后变化如下:
关于导入excel时js转换时间的正确方式
文章图片


二、问题描述 【关于导入excel时js转换时间的正确方式】往往我们在做excel导入的时候,解析出来的是一个数字时间,这时候就有必要进行时间格式化转换了!

三、解决思路 1、用1970-1-1减去1900-1-1得到相差为:25567天 0小时 5分钟 43秒;
2、减去多出来的1天8小时;
js代码如下:
let time = new Date((43831-25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000- 24 * 3600000 - 8 * 3600000)let year = time.getFullYear() + ''console.log('year:'+year)let month = time.getMonth() + 1 + ''console.log('month:'+month)let date = time.getDate() + ''console.log('data:'+date)

关于导入excel时js转换时间的正确方式
文章图片


附:js读取excel中日期格式转换问题 在使用js-xlsx插件来读取excel时,会将2018/10/16这种数据自动装换成48264.12584511.
所以需要自己手动再转换回来
// excel读取2018/01/01这种时间格式是会将它装换成数字类似于46254.1545151415 numb是传过来的整数数字,format是之间间隔的符号formatDate(numb, format) {const time = new Date((numb - 1) * 24 * 3600000 + 1)time.setYear(time.getFullYear() - 70)const year = time.getFullYear() + ''const month = time.getMonth() + 1 + ''const date = time.getDate() - 1 + ''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(42618, '/')) // 2016-9-5


总结 到此这篇关于导入excel时js转换时间的正确方式的文章就介绍到这了,更多相关导入excel时js转换时间内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读