前端js讀取excel、xlsx文件日期被轉為數字,日期格式轉換


記錄一下,日常debug

網上最普遍的方法

`function 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 ;
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
    }`

但是親測這個方法有誤差,算出來的時間有可能會少一天,比如我excel里面輸入的是2022/03/08,轉換數字為44628.
轉換出來確是2022/03/07

正確的算法應該是:
`function formatDate(numb, format) {
        const old = numb - 1;
        const t = Math.round((old - Math.floor(old)) * 24 * 60 * 60);
        const time = new Date(1900, 0, old, 0, 0, t)
        const year = time.getFullYear() ;
        const month = time.getMonth() + 1 ;
        const date = time.getDate() ;
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
    }`


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM