Problem : I encountered a problem in the process of working on the project. When importing excel data, I found that the format of the date was wrong. The expected effect is 2022/1/2, but the effect after importing is 44563. After consulting the data, it is found that 44563 represents the number of days between January 1, 1900 and January 2, 2022.
Method 1 (not recommended)
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)
},
This method has certain flaws, and there will be deviations at certain specific times. For example, on the day of 2022/03/08, after importing the input, it will display 2022/03/07. One day less than the original data.
Method 2 (recommended)
formatDate(numb, format) {
//参数numb是间隔天数,format是自定义的日期分隔符。
console.log(numb)
//打印出来的结果是44563,表示1900年1月1日到当前日期的天数
let getDay = numb - 1
let t = Math.round((getDay - Math.floor(getDay)) * 24 * 60 * 60)
//当导入的excel日期中包含了时分秒,t则表示小数点后面的时间
let time = new Date(1900, 0, getDay, 0, 0, t);
//getDay是从1900开始计算的,因此new Date()的第一个参数是1900
let year = time.getFullYear();
let month = time.getMonth() + 1;
let date = time.getDate();
return year + format + (month < 10 ? "0" + month : month) + format + (date < 10 ? "0" + date : date);
},
This method can perfectly solve the problem of wrong date format when JS reads Excel, and I hope it can be helpful to everyone.