2

How do i convert this excel dataserial value 41225 back to date format 12-Nov-2012 using phpexcel and code igniter?

I have tried the following but it didn't work.

$G74 = $objPHPExcel->getActiveSheet()->getCell('B6')->getValue();
Paul Dessert
  • 6,363
  • 8
  • 47
  • 74
H Dindi
  • 1,484
  • 6
  • 39
  • 68

3 Answers3

11

Dates in Excel are stored as number of days since 1st Jan 1900, except there is an off by one error due to 1900 not being a leap year. You can create therefore a DateTime object with this hack (valid for dates from 1st March 1900 onwards):

$n = 41225;
$dateTime = new DateTime("1899-12-30 + $n days");

You can format the DateTime Object with something like:

echo $dateTime->format("d M Y");

If you want to include the time as well as the date, multiply by 86400 (the number of seconds in a day) to get seconds since 1st Jan 1900 before you convert:

$n = 42898.35416666;
$dateTime = new DateTime("1899-12-30 + ". round($n * 86400) . " seconds");
rjmunro
  • 27,203
  • 20
  • 110
  • 132
3

Using the getFormattedValue() method rather than getValue() might help if the cell has a format mask that formats it as a date. getValue() returns a raw value, which (in this case) is the Excel serialized number.

Otherwise, the ExcelToPHP() or ExcelToPHPObject() methods in the PHPExcel_Shared_Date class should do the job of returning a unix timestamp or a PHP DateTime object that you can then format however you wish

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

I had to convert a dateserial number in decimal format ie: 42898.35416666 and the DateTime object does not take decimals.

Based on rjmunro's answer, and animuson's answer on how to convert decimals to hours and minutes, here is a solution for decimal Excel dates.

function dateSerialToDateTime($dateserial) {
    $arrDate = explode(".", $dateserial);
    $n = $arrDate[0];
    $decimal = "." . $arrDate[1];  //decimal amount of seconds
    $duration = 86400 * $decimal;  //number of seconds in a day * decimal

    $dateTime = new DateTime("1899-12-30 + $n days");
    $converted = $dateTime->format("Y-m-d") . " " . gmdate("H:i:s", $duration);

    return $converted;
}
$dateserial = 42898.35416666;
die(dateSerialToDateTime($dateserial));

//returns 2017-06-12 08:29:59
Nicolas Giszpenc
  • 677
  • 6
  • 11
  • You could probably just convert the the whole thing to seconds by multiplying by 86400: `$a = new DateTime("1899-12-30 + ". floor($n * 86400) . " seconds");` – rjmunro Sep 29 '17 at 08:57