在实际应用中PHP读取的Excel文件的日期无法直接使用,会出现的一系列问题。
正常日期 | Excel存储 |
---|---|
2023-1-1 | 44927 |
2023-1-1 23:59:59 | 44927.9999884259 |
通过PHPExcel的官方文档了解到,我们可以得到一个新的的计算公式:
Excel日期与PHP时间戳之间存在一个时间偏移量,因为Excel的日期起点是1900年1月1日,在UNIX时间戳中相当于从1970年1月1日起前推的25569天。
/*
* $excel_date Excel表格的数字
* 25569 (常数)日期的偏移量
* 86400 (60*60*24)
* 28800 (60*60*8)时差
*/
$timestamp = ($excel_date - 25569) * 86400 - 28800;
通过上述公式,获取Excel日期
function get_excel_timestamp($excel_date)
{
$pattern = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/'; //日期格式正则
if (empty($excel_date)) {
return time();
} elseif (is_numeric($excel_date)) {
return ($excel_date - 25569) * 86400 - 28800;
} elseif (preg_match($pattern, $excel_date)) {
return strtotime($excel_date);
} else {
return time();
}
}