我们在excel导入的时候日期会是一串58241.25这种。
查证文档后发现资料----各个语言日期转化成时间戳http://coolaf.com/tool/unix
Microsoft Excel的日期格式转换需要这样
=(A1 / 86400) + 25569 Format the result cell for date/time, the result will be in GMT time (A1 is the cell with the epoch number). For other time zones: =((A1 +/- time zone adjustment) / 86400) + 25569.
方法如下:
function ExcelDateToJSDate(serial) {
var utc_days = Math.floor(serial - 25569);
var utc_value = utc_days * 86400;
var date_info = new Date(utc_value * 1000);
var fractional_day = serial - Math.floor(serial) + 0.0000001;
var total_seconds = Math.floor(86400 * fractional_day);
var seconds = total_seconds % 60;
total_seconds -= seconds;
var hours = Math.floor(total_seconds / (60 * 60));
var minutes = Math.floor(total_seconds / 60) % 60;
return new Date(date_info.getFullYear(), date_info.getMonth(), date_info.getDate(), hours, minutes, seconds);
}
就这么解决时间转化的问题。
网上有一种错误的方法我贴出来:
function formatDate(numb, format) {
if (!numb) {
return "";
}
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() + ''
/* if (format && format.length === 1) {
return year + format + month + format + date
} */
return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
}
这种转化会出现错误,比如2038/12/31日 的excel值 50770 就变成2039-01-01了,应该是时区没有考虑进去导致的问题。
如果需要js日期转为excel日期可用下面方法:
function JSDateToExcelDate(inDate) {
var returnDateTime = 25569.0 + ((inDate.getTime() - (inDate.getTimezoneOffset() * 60 * 1000)) / (1000 * 60 * 60 * 24));
return returnDateTime.toString().substr(0,5);
}
现在就写这么多了,忙去了。
网友评论