| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\OpenSpout\Writer\XLSX\Helper; |
| 4 |
|
| 5 |
class DateHelper |
| 6 |
{ |
| 7 |
/** |
| 8 |
* @see https://github.com/PHPOffice/PhpSpreadsheet/blob/1.22.0/src/PhpSpreadsheet/Shared/Date.php#L296 |
| 9 |
* |
| 10 |
* @return float |
| 11 |
*/ |
| 12 |
public static function toExcel(\DateTimeInterface $dateTime) |
| 13 |
{ |
| 14 |
$year = (int) $dateTime->format('Y'); |
| 15 |
$month = (int) $dateTime->format('m'); |
| 16 |
$day = (int) $dateTime->format('d'); |
| 17 |
$hours = (int) $dateTime->format('H'); |
| 18 |
$minutes = (int) $dateTime->format('i'); |
| 19 |
$seconds = (int) $dateTime->format('s'); |
| 20 |
// Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel |
| 21 |
// This affects every date following 28th February 1900 |
| 22 |
$excel1900isLeapYear = \true; |
| 23 |
if (1900 === $year && $month <= 2) { |
| 24 |
$excel1900isLeapYear = \false; |
| 25 |
} |
| 26 |
$myexcelBaseDate = 2415020; |
| 27 |
// Julian base date Adjustment |
| 28 |
if ($month > 2) { |
| 29 |
$month -= 3; |
| 30 |
} else { |
| 31 |
$month += 9; |
| 32 |
--$year; |
| 33 |
} |
| 34 |
// Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) |
| 35 |
$century = (int) \substr((string) $year, 0, 2); |
| 36 |
$decade = (int) \substr((string) $year, 2, 2); |
| 37 |
$excelDate = \floor(146097 * $century / 4) + \floor(1461 * $decade / 4) + \floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear; |
| 38 |
$excelTime = ($hours * 3600 + $minutes * 60 + $seconds) / 86400; |
| 39 |
return (float) $excelDate + $excelTime; |
| 40 |
} |
| 41 |
} |
| 42 |
|