将 PHP 单元格值转换为日期

Converting PHP cell value to date

PHPExcel 在同一个 sheet 模板上给我不同的日期值格式

这是我使用的代码

$value = $this->worksheet->getCellByColumnAndRow(11, 1)  ->getFormattedValue();
$this->_date = DateTime::createFromFormat("j/n/Y",$value);

我尝试了以下答案,但没有解决

how to get date from excel using PHPExcel library

这是我遇到的一个问题,希望能帮助到同样遇到这个问题的其他人。

这帮我解决了

$value = $this->worksheet->getCellByColumnAndRow(11, 1)  ->getCalculatedValue();
$timeValue = (string)PHPExcel_Style_NumberFormat::toFormattedString($value,PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
$this->_date = DateTime::createFromFormat("Y-m-d",$timeValue);

您可以将 Excel 序列化时间戳值直接转换为 PHP DateTime 对象,无需创建格式化字符串,然后从中创建新的 DateTime 对象:

$msExcelSerializedTimestampValue = $this->worksheet
    ->getCellByColumnAndRow(11, 1)
    ->getCalculatedValue();  // getValue() is even easier if the cell doesn't contain a formula
$this->_date = PHPExcel_Shared_Date::ExcelToPHPObject($msExcelSerializedTimestampValue);