|
9 | 9 |
|
10 | 10 | final class Date implements CellStyleInterface
|
11 | 11 | {
|
12 |
| - public function decorateValue($value) |
| 12 | + public function decorateValue($value): ?int |
13 | 13 | {
|
14 |
| - if (empty($value)) { |
15 |
| - return $value; |
| 14 | + if (! \is_string($value) || 1 !== \preg_match('/^(?<year>\d\d\d\d)-(?<month>\d\d)-(?<day>\d\d)$/', $value, $matches)) { |
| 15 | + return null; |
16 | 16 | }
|
17 | 17 |
|
18 |
| - return \implode('/', \array_reverse(\explode('-', $value))); |
| 18 | + $year = (int) $matches['year']; |
| 19 | + $month = (int) $matches['month']; |
| 20 | + $day = (int) $matches['day']; |
| 21 | + |
| 22 | + // Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel |
| 23 | + // This affects every date following 28th February 1900 |
| 24 | + $excel1900isLeapYear = true; |
| 25 | + if ((1900 === $year) && ($month <= 2)) { |
| 26 | + $excel1900isLeapYear = false; |
| 27 | + } |
| 28 | + $myexcelBaseDate = 2415020; |
| 29 | + |
| 30 | + // Julian base date Adjustment |
| 31 | + if ($month > 2) { |
| 32 | + $month -= 3; |
| 33 | + } else { |
| 34 | + $month += 9; |
| 35 | + --$year; |
| 36 | + } |
| 37 | + |
| 38 | + // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) |
| 39 | + $century = (int) \substr((string) $year, 0, 2); |
| 40 | + $decade = (int) \substr((string) $year, 2, 2); |
| 41 | + $excelDate = \floor((146097 * $century) / 4) + \floor((1461 * $decade) / 4) + \floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear; |
| 42 | + |
| 43 | + return (int) $excelDate; |
19 | 44 | }
|
20 | 45 |
|
21 | 46 | public function styleCell(Format $format): void
|
22 | 47 | {
|
23 | 48 | $format->setAlign('center');
|
| 49 | + $format->setNumFormat('DD/MM/YYYY'); |
24 | 50 | }
|
25 | 51 | }
|
0 commit comments