Regarding the problem that Excel's (year/month/day) date is five digits when js is imported into Excel

Contents of this article


Urgently needed code can jump directly to the final code~

Preface

Recently, a front-end importing Excel requirement was realized, and then the problem came. The date passed by Excel is a string of numbers! ! !
For example: October 28, 2020 is 44132. According to Du Niang, the date stored in Excel is calculated in days starting from January 1, 1900, which means that January 1, 1900 is 1 in Excel.
Date format for October 28, 2020
Excel record format

Ideas

My initial thoughts were:

Because the timestamp is calculated from January 1, 1970 (when the timestamp is 0, it is January 1, 1970) that is new Date(0).toLocaleDateString('zh'), the value is 1970/1/1.
And the day of January 1, 1970 is in Excel 25569, so subtract 25569 from the value obtained in Excel, and then multiply 24*60*60*1000it by the number of milliseconds to get to this day, and then new Date(这个毫秒数)you can get the converted date.

But just before writing this blog, I tested it again and found that there are loopholes in this writing...

That is, when the value of Excel is less than 61, the conversion time differs from the normal time by one day
The cause of the vulnerability

The cause of the problem:

In Excel:

  • 1 is January 01, 1900
  • 59 is February 28, 1900
  • 60 is February 29, 1900 , 1900 is a normal year, there is no such day! ! ! The reason for the error is this
  • 61 is March 01, 1900
  • 62 is March 02, 1900

Solution : Since there is a difference of one day before 60, make a judgment and subtract one more day when <60

Final code

The final code after solving and testing by myself is as follows (only applicable to 年月日date conversion in Excel 不包含时分秒):

/**
 * 格式化Excel表格中存储的时间
 * @param {Number} num:	excel存储的数字
 * @param {String} format: 年月日的间隔符,默认为'-'
 */
function formatExcelTime(num, format = '-') {
    
    
	num = Number(num);	// 强制类型转化,以防传来的值是字符串
	let millisecond = 0;	// 转化后的毫秒数
	if (num > 60) {
    
    
		millisecond = (num - 25569) * 60 * 60 * 24 * 1000;
	} else {
    
    
		millisecond = (num - 25568) * 60 * 60 * 24 * 1000;
	}
	let date = new Date(millisecond);	// 根据转化后的毫秒数获取对应的时间
	let yy = date.getFullYear();
	let mm = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
	let dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
	return yy + format + mm + format + dd;	// 返回格式化后的日期
}

Guess you like

Origin blog.csdn.net/qq_40662765/article/details/109326067