PHPExcel, Date being parsed incorrectly

混江龙づ霸主 提交于 2019-12-05 11:14:29
steve

Using PHPExcel v1.7.9

Open file "PHPExcel\Style\NumberFormat.php"

Go to Line 278:

self::$_builtInFormats[22] = 'm/d/yy h:mm'; 

replace with

self::$_builtInFormats[22] = 'dd-mm-yyyy hh:mm';

or whatever format you want.

I can't find an efficient way to change it on the fly and I have no reason to ever format the date in any way other than this so this solution works for me.

Using v1.7.8 and assuming Excel2007 aka .xlsx file

$a1Cell = $sheet->getCell('A1');
$a1CellFormattedValue = trim($a1Cell->getFormattedValue());
if (!empty($a1CellFormattedValue)) {
    $dateInTimestampValue = PHPExcel_Shared_Date::ExcelToPHP($a1Cell->getValue());
}

Let me explain each line.

  • line 1 is to get the Cell object
  • line 2 and the if block is so that we only perform for non-empty cells
  • line 4 is how we transform the value inside the cell into unix timestamp.

You're left with deciding what date formats to write the value into the destination excel file. My suggestion is that you decide with the stakeholders that ALL dates in destination excel files will follow a particular format.

This is the cleanest way I can think of.

P.S. If you have an empty cell, and you try to do the PHPExcel_Shared_Date::ExcelToPHP on the cell value, you will get the current date.

UPDATE

Just realized that your comments mention you cannot arbitrarily decide the format. Sorry about that. If I come across something that helps, I will update this answer.

I just came across your question. if you know the format in which excel is saving date, then you can use the PHP class DateTime as an intermediate date representation

$data=$sheet->getCell("D9")->getFormattedValue();
$date = DateTime::createFromFormat ("m-d-y" , $data);
$string_date = $date->format($format);

where $format is any format you want

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!