1. 程式人生 > 程式設計 >關於匯入excel時js轉換時間的正確方式

關於匯入excel時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匯入的時候,解析出來的是一個數字時間,這時候就有必要進行時間格式化轉換了!

三、解決思路

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) + (dateSltumEXEC
< 10 ? '0' + date : date) },  console.log(fwww.cppcns.comormatDate(42618,'/')) // 2016-9-5

總結

到此這篇關於匯入excel時js轉換時間的正確方式的文章就介紹到這了,更多相關匯入excel時js轉換時間內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!