Date   F
last analyzed

Complexity

Total Complexity 83

Size/Duplication

Total Lines 542
Duplicated Lines 0 %

Test Coverage

Coverage 99.48%

Importance

Changes 0
Metric Value
wmc 83
eloc 202
dl 0
loc 542
ccs 192
cts 193
cp 0.9948
rs 2
c 0
b 0
f 0

23 Methods

Rating   Name   Duplication   Size   Complexity  
A formattedPHPToExcel() 0 33 5
A isDateTimeFormat() 0 3 1
A dateTimeToExcel() 0 11 1
A excelToTimestamp() 0 6 1
A timestampToExcel() 0 7 2
A PHPToExcel() 0 11 5
B convertIsoDate() 0 23 7
A getDefaultOrLocalTimezone() 0 3 1
A validateTimeZone() 0 10 4
A setDefaultTimezone() 0 11 2
A getDefaultTimezone() 0 3 1
A setExcelCalendar() 0 12 3
A getExcelCalendar() 0 3 1
A getDefaultTimezoneOrNull() 0 3 1
A stringToExcel() 0 24 6
A roundMicroseconds() 0 7 3
A dayStringToNumber() 0 8 2
A formattedDateTimeFromTimestamp() 0 5 1
A isDateTime() 0 25 6
C isDateTimeFormatCode() 0 52 14
A monthStringToNumber() 0 11 4
B excelToDateTimeObject() 0 44 10
A dateTimeFromTimestamp() 0 6 2

How to fix   Complexity   

Complex Class

Complex classes like Date often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Date, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Shared;
4
5
use DateTime;
6
use DateTimeInterface;
7
use DateTimeZone;
8
use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel;
9
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
10
use PhpOffice\PhpSpreadsheet\Cell\Cell;
11
use PhpOffice\PhpSpreadsheet\Exception;
12
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
13
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
14
15
class Date
16
{
17
    /** constants */
18
    const CALENDAR_WINDOWS_1900 = 1900; //    Base date of 1st Jan 1900 = 1.0
19
    const CALENDAR_MAC_1904 = 1904; //    Base date of 2nd Jan 1904 = 1.0
20
21
    /**
22
     * Names of the months of the year, indexed by shortname
23
     * Planned usage for locale settings.
24
     *
25
     * @var string[]
26
     */
27
    public static array $monthNames = [
28
        'Jan' => 'January',
29
        'Feb' => 'February',
30
        'Mar' => 'March',
31
        'Apr' => 'April',
32
        'May' => 'May',
33
        'Jun' => 'June',
34
        'Jul' => 'July',
35
        'Aug' => 'August',
36
        'Sep' => 'September',
37
        'Oct' => 'October',
38
        'Nov' => 'November',
39
        'Dec' => 'December',
40
    ];
41
42
    /**
43
     * @var string[]
44
     */
45
    public static array $numberSuffixes = [
46
        'st',
47
        'nd',
48
        'rd',
49
        'th',
50
    ];
51
52
    /**
53
     * Base calendar year to use for calculations
54
     * Value is either CALENDAR_WINDOWS_1900 (1900) or CALENDAR_MAC_1904 (1904).
55
     */
56
    protected static int $excelCalendar = self::CALENDAR_WINDOWS_1900;
57
58
    /**
59
     * Default timezone to use for DateTime objects.
60
     */
61
    protected static ?DateTimeZone $defaultTimeZone = null;
62
63
    /**
64
     * Set the Excel calendar (Windows 1900 or Mac 1904).
65
     *
66
     * @param ?int $baseYear Excel base date (1900 or 1904)
67
     *
68
     * @return bool Success or failure
69
     */
70 9625
    public static function setExcelCalendar(?int $baseYear): bool
71
    {
72
        if (
73 9625
            ($baseYear === self::CALENDAR_WINDOWS_1900)
74 9625
            || ($baseYear === self::CALENDAR_MAC_1904)
75
        ) {
76 9625
            self::$excelCalendar = $baseYear;
77
78 9625
            return true;
79
        }
80
81 1
        return false;
82
    }
83
84
    /**
85
     * Return the Excel calendar (Windows 1900 or Mac 1904).
86
     *
87
     * @return int Excel base date (1900 or 1904)
88
     */
89 10120
    public static function getExcelCalendar(): int
90
    {
91 10120
        return self::$excelCalendar;
92
    }
93
94
    /**
95
     * Set the Default timezone to use for dates.
96
     *
97
     * @param null|DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions
98
     *
99
     * @return bool Success or failure
100
     */
101 147
    public static function setDefaultTimezone($timeZone): bool
102
    {
103
        try {
104 147
            $timeZone = self::validateTimeZone($timeZone);
105 147
            self::$defaultTimeZone = $timeZone;
106 147
            $retval = true;
107 1
        } catch (PhpSpreadsheetException) {
108 1
            $retval = false;
109
        }
110
111 147
        return $retval;
112
    }
113
114
    /**
115
     * Return the Default timezone, or UTC if default not set.
116
     */
117 2336
    public static function getDefaultTimezone(): DateTimeZone
118
    {
119 2336
        return self::$defaultTimeZone ?? new DateTimeZone('UTC');
120
    }
121
122
    /**
123
     * Return the Default timezone, or local timezone if default is not set.
124
     */
125 1009
    public static function getDefaultOrLocalTimezone(): DateTimeZone
126
    {
127 1009
        return self::$defaultTimeZone ?? new DateTimeZone(date_default_timezone_get());
128
    }
129
130
    /**
131
     * Return the Default timezone even if null.
132
     */
133 147
    public static function getDefaultTimezoneOrNull(): ?DateTimeZone
134
    {
135 147
        return self::$defaultTimeZone;
136
    }
137
138
    /**
139
     * Validate a timezone.
140
     *
141
     * @param null|DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object
142
     *
143
     * @return ?DateTimeZone The timezone as a timezone object
144
     */
145 165
    private static function validateTimeZone($timeZone): ?DateTimeZone
146
    {
147 165
        if ($timeZone instanceof DateTimeZone || $timeZone === null) {
148 165
            return $timeZone;
149
        }
150 26
        if (in_array($timeZone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC))) {
151 25
            return new DateTimeZone($timeZone);
152
        }
153
154 1
        throw new PhpSpreadsheetException('Invalid timezone');
155
    }
156
157
    /**
158
     * @param mixed $value Converts a date/time in ISO-8601 standard format date string to an Excel
159
     *                         serialized timestamp.
160
     *                     See https://en.wikipedia.org/wiki/ISO_8601 for details of the ISO-8601 standard format.
161
     */
162 20
    public static function convertIsoDate(mixed $value): float|int
163
    {
164 20
        if (!is_string($value)) {
165 1
            throw new Exception('Non-string value supplied for Iso Date conversion');
166
        }
167
168 19
        $date = new DateTime($value);
169 19
        $dateErrors = DateTime::getLastErrors();
170
171 19
        if (is_array($dateErrors) && ($dateErrors['warning_count'] > 0 || $dateErrors['error_count'] > 0)) {
172 1
            throw new Exception("Invalid string $value supplied for datatype Date");
173
        }
174
175 18
        $newValue = self::PHPToExcel($date);
176 18
        if ($newValue === false) {
177
            throw new Exception("Invalid string $value supplied for datatype Date");
178
        }
179
180 18
        if (preg_match('/^\s*\d?\d:\d\d(:\d\d([.]\d+)?)?\s*(am|pm)?\s*$/i', $value) == 1) {
181 4
            $newValue = fmod($newValue, 1.0);
182
        }
183
184 18
        return $newValue;
185
    }
186
187
    /**
188
     * Convert a MS serialized datetime value from Excel to a PHP Date/Time object.
189
     *
190
     * @param float|int $excelTimestamp MS Excel serialized date/time value
191
     * @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp,
192
     *                                           if you don't want to treat it as a UTC value
193
     *                                           Use the default (UTC) unless you absolutely need a conversion
194
     *
195
     * @return DateTime PHP date/time object
196
     */
197 2373
    public static function excelToDateTimeObject(float|int $excelTimestamp, null|DateTimeZone|string $timeZone = null): DateTime
198
    {
199 2373
        $timeZone = ($timeZone === null) ? self::getDefaultTimezone() : self::validateTimeZone($timeZone);
200 2373
        if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) {
201 2350
            if ($excelTimestamp < 1 && self::$excelCalendar === self::CALENDAR_WINDOWS_1900) {
202
                // Unix timestamp base date
203 188
                $baseDate = new DateTime('1970-01-01', $timeZone);
204
            } else {
205
                // MS Excel calendar base dates
206 2173
                if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) {
207
                    // Allow adjustment for 1900 Leap Year in MS Excel
208 2077
                    $baseDate = ($excelTimestamp < 60) ? new DateTime('1899-12-31', $timeZone) : new DateTime('1899-12-30', $timeZone);
209
                } else {
210 98
                    $baseDate = new DateTime('1904-01-01', $timeZone);
211
                }
212
            }
213
        } else {
214 23
            $baseDate = new DateTime('1899-12-30', $timeZone);
215
        }
216
217 2373
        if (is_int($excelTimestamp)) {
218 105
            if ($excelTimestamp >= 0) {
219 105
                return $baseDate->modify("+ $excelTimestamp days");
220
            }
221
222 1
            return $baseDate->modify("$excelTimestamp days");
223
        }
224 2296
        $days = floor($excelTimestamp);
225 2296
        $partDay = $excelTimestamp - $days;
226 2296
        $hms = 86400 * $partDay;
227 2296
        $microseconds = (int) round(fmod($hms, 1) * 1000000);
228 2296
        $hms = (int) floor($hms);
229 2296
        $hours = intdiv($hms, 3600);
230 2296
        $hms -= $hours * 3600;
231 2296
        $minutes = intdiv($hms, 60);
232 2296
        $seconds = $hms % 60;
233
234 2296
        if ($days >= 0) {
235 2291
            $days = '+' . $days;
236
        }
237 2296
        $interval = $days . ' days';
238
239 2296
        return $baseDate->modify($interval)
240 2296
            ->setTime($hours, $minutes, $seconds, $microseconds);
241
    }
242
243
    /**
244
     * Convert a MS serialized datetime value from Excel to a unix timestamp.
245
     * The use of Unix timestamps, and therefore this function, is discouraged.
246
     * They are not Y2038-safe on a 32-bit system, and have no timezone info.
247
     *
248
     * @param float|int $excelTimestamp MS Excel serialized date/time value
249
     * @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp,
250
     *                                               if you don't want to treat it as a UTC value
251
     *                                               Use the default (UTC) unless you absolutely need a conversion
252
     *
253
     * @return int Unix timetamp for this date/time
254
     */
255 55
    public static function excelToTimestamp($excelTimestamp, $timeZone = null): int
256
    {
257 55
        $dto = self::excelToDateTimeObject($excelTimestamp, $timeZone);
258 55
        self::roundMicroseconds($dto);
259
260 55
        return (int) $dto->format('U');
261
    }
262
263
    /**
264
     * Convert a date from PHP to an MS Excel serialized date/time value.
265
     *
266
     * @param mixed $dateValue PHP DateTime object or a string - Unix timestamp is also permitted, but discouraged;
267
     *    not Y2038-safe on a 32-bit system, and no timezone info
268
     *
269
     * @return false|float Excel date/time value
270
     *                                  or boolean FALSE on failure
271
     */
272 294
    public static function PHPToExcel(mixed $dateValue)
273
    {
274 294
        if ((is_object($dateValue)) && ($dateValue instanceof DateTimeInterface)) {
275 289
            return self::dateTimeToExcel($dateValue);
276 11
        } elseif (is_numeric($dateValue)) {
277 10
            return self::timestampToExcel($dateValue);
278 7
        } elseif (is_string($dateValue)) {
279 1
            return self::stringToExcel($dateValue);
280
        }
281
282 6
        return false;
283
    }
284
285
    /**
286
     * Convert a PHP DateTime object to an MS Excel serialized date/time value.
287
     *
288
     * @param DateTimeInterface $dateValue PHP DateTime object
289
     *
290
     * @return float MS Excel serialized date/time value
291
     */
292 343
    public static function dateTimeToExcel(DateTimeInterface $dateValue): float
293
    {
294 343
        $seconds = (float) sprintf('%d.%06d', $dateValue->format('s'), $dateValue->format('u'));
295
296 343
        return self::formattedPHPToExcel(
297 343
            (int) $dateValue->format('Y'),
298 343
            (int) $dateValue->format('m'),
299 343
            (int) $dateValue->format('d'),
300 343
            (int) $dateValue->format('H'),
301 343
            (int) $dateValue->format('i'),
302 343
            $seconds
303 343
        );
304
    }
305
306
    /**
307
     * Convert a Unix timestamp to an MS Excel serialized date/time value.
308
     * The use of Unix timestamps, and therefore this function, is discouraged.
309
     * They are not Y2038-safe on a 32-bit system, and have no timezone info.
310
     *
311
     * @param float|int|string $unixTimestamp Unix Timestamp
312
     *
313
     * @return false|float MS Excel serialized date/time value
314
     */
315 28
    public static function timestampToExcel($unixTimestamp): bool|float
316
    {
317 28
        if (!is_numeric($unixTimestamp)) {
318 1
            return false;
319
        }
320
321 27
        return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp));
322
    }
323
324
    /**
325
     * formattedPHPToExcel.
326
     *
327
     * @return float Excel date/time value
328
     */
329 2765
    public static function formattedPHPToExcel(int $year, int $month, int $day, int $hours = 0, int $minutes = 0, float|int $seconds = 0): float
330
    {
331 2765
        if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) {
332
            //
333
            //    Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel
334
            //    This affects every date following 28th February 1900
335
            //
336 2696
            $excel1900isLeapYear = true;
337 2696
            if (($year == 1900) && ($month <= 2)) {
338 241
                $excel1900isLeapYear = false;
339
            }
340 2696
            $myexcelBaseDate = 2415020;
341
        } else {
342 71
            $myexcelBaseDate = 2416481;
343 71
            $excel1900isLeapYear = false;
344
        }
345
346
        //    Julian base date Adjustment
347 2765
        if ($month > 2) {
348 1828
            $month -= 3;
349
        } else {
350 1750
            $month += 9;
351 1750
            --$year;
352
        }
353
354
        //    Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
355 2765
        $century = (int) substr((string) $year, 0, 2);
356 2765
        $decade = (int) substr((string) $year, 2, 2);
357 2765
        $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear;
358
359 2765
        $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
360
361 2765
        return (float) $excelDate + $excelTime;
362
    }
363
364
    /**
365
     * Is a given cell a date/time?
366
     */
367 9
    public static function isDateTime(Cell $cell, mixed $value = null, bool $dateWithoutTimeOkay = true): bool
368
    {
369 9
        $result = false;
370 9
        $worksheet = $cell->getWorksheetOrNull();
371 9
        $spreadsheet = ($worksheet === null) ? null : $worksheet->getParent();
372 9
        if ($worksheet !== null && $spreadsheet !== null) {
373 9
            $index = $spreadsheet->getActiveSheetIndex();
374 9
            $selected = $worksheet->getSelectedCells();
375
376
            try {
377 9
                $result = is_numeric($value ?? $cell->getCalculatedValue())
378 9
                    && self::isDateTimeFormat(
379 9
                        $worksheet->getStyle(
380 9
                            $cell->getCoordinate()
381 9
                        )->getNumberFormat(),
382 9
                        $dateWithoutTimeOkay
383 9
                    );
384 1
            } catch (Exception) {
385
                // Result is already false, so no need to actually do anything here
386
            }
387 9
            $worksheet->setSelectedCells($selected);
388 9
            $spreadsheet->setActiveSheetIndex($index);
389
        }
390
391 9
        return $result;
392
    }
393
394
    /**
395
     * Is a given NumberFormat code a date/time format code?
396
     */
397 9
    public static function isDateTimeFormat(NumberFormat $excelFormatCode, bool $dateWithoutTimeOkay = true): bool
398
    {
399 9
        return self::isDateTimeFormatCode((string) $excelFormatCode->getFormatCode(), $dateWithoutTimeOkay);
400
    }
401
402
    private const POSSIBLE_DATETIME_FORMAT_CHARACTERS = 'eymdHs';
403
    private const POSSIBLE_TIME_FORMAT_CHARACTERS = 'Hs'; // note - no 'm' due to ambiguity
404
405
    /**
406
     * Is a given number format code a date/time?
407
     */
408 99
    public static function isDateTimeFormatCode(string $excelFormatCode, bool $dateWithoutTimeOkay = true): bool
409
    {
410 99
        if (strtolower($excelFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) {
411
            //    "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check)
412 29
            return false;
413
        }
414 75
        if (preg_match('/[0#]E[+-]0/i', $excelFormatCode)) {
415
            //    Scientific format
416 1
            return false;
417
        }
418
419
        // Switch on formatcode
420 75
        $excelFormatCode = (string) NumberFormat::convertSystemFormats($excelFormatCode);
421 75
        if (in_array($excelFormatCode, NumberFormat::DATE_TIME_OR_DATETIME_ARRAY, true)) {
422 31
            return $dateWithoutTimeOkay || in_array($excelFormatCode, NumberFormat::TIME_OR_DATETIME_ARRAY);
423
        }
424
425
        //    Typically number, currency or accounting (or occasionally fraction) formats
426 48
        if ((str_starts_with($excelFormatCode, '_')) || (str_starts_with($excelFormatCode, '0 '))) {
427 1
            return false;
428
        }
429
        // Some "special formats" provided in German Excel versions were detected as date time value,
430
        // so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany).
431 47
        if (str_contains($excelFormatCode, '-00000')) {
432 2
            return false;
433
        }
434 45
        $possibleFormatCharacters = $dateWithoutTimeOkay ? self::POSSIBLE_DATETIME_FORMAT_CHARACTERS : self::POSSIBLE_TIME_FORMAT_CHARACTERS;
435
        // Try checking for any of the date formatting characters that don't appear within square braces
436 45
        if (preg_match('/(^|\])[^\[]*[' . $possibleFormatCharacters . ']/i', $excelFormatCode)) {
437
            //    We might also have a format mask containing quoted strings...
438
            //        we don't want to test for any of our characters within the quoted blocks
439 31
            if (str_contains($excelFormatCode, '"')) {
440 7
                $segMatcher = false;
441 7
                foreach (explode('"', $excelFormatCode) as $subVal) {
442
                    //    Only test in alternate array entries (the non-quoted blocks)
443 7
                    $segMatcher = $segMatcher === false;
444
                    if (
445 7
                        $segMatcher
446 7
                        && (preg_match('/(^|\])[^\[]*[' . $possibleFormatCharacters . ']/i', $subVal))
447
                    ) {
448 6
                        return true;
449
                    }
450
                }
451
452 1
                return false;
453
            }
454
455 29
            return true;
456
        }
457
458
        // No date...
459 19
        return false;
460
    }
461
462
    /**
463
     * Convert a date/time string to Excel time.
464
     *
465
     * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10'
466
     *
467
     * @return false|float Excel date/time serial value
468
     */
469 182
    public static function stringToExcel(string $dateValue): bool|float
470
    {
471 182
        if (strlen($dateValue) < 2) {
472 27
            return false;
473
        }
474 157
        if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2})?)?$/iu', $dateValue)) {
475 154
            return false;
476
        }
477
478 9
        $dateValueNew = DateTimeExcel\DateValue::fromString($dateValue);
479
480 9
        if (!is_float($dateValueNew)) {
481 2
            return false;
482
        }
483
484 8
        if (str_contains($dateValue, ':')) {
485 2
            $timeValue = DateTimeExcel\TimeValue::fromString($dateValue);
486 2
            if (!is_float($timeValue)) {
487 1
                return false;
488
            }
489 2
            $dateValueNew += $timeValue;
490
        }
491
492 8
        return $dateValueNew;
493
    }
494
495
    /**
496
     * Converts a month name (either a long or a short name) to a month number.
497
     *
498
     * @param string $monthName Month name or abbreviation
499
     *
500
     * @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name
501
     */
502 12
    public static function monthStringToNumber(string $monthName)
503
    {
504 12
        $monthIndex = 1;
505 12
        foreach (self::$monthNames as $shortMonthName => $longMonthName) {
506 12
            if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) {
507 6
                return $monthIndex;
508
            }
509 12
            ++$monthIndex;
510
        }
511
512 6
        return $monthName;
513
    }
514
515
    /**
516
     * Strips an ordinal from a numeric value.
517
     *
518
     * @param string $day Day number with an ordinal
519
     *
520
     * @return int|string The integer value with any ordinal stripped, or the original string argument if it isn't a valid numeric
521
     */
522 18
    public static function dayStringToNumber(string $day)
523
    {
524 18
        $strippedDayValue = (str_replace(self::$numberSuffixes, '', $day));
525 18
        if (is_numeric($strippedDayValue)) {
526 15
            return (int) $strippedDayValue;
527
        }
528
529 3
        return $day;
530
    }
531
532 1015
    public static function dateTimeFromTimestamp(string $date, ?DateTimeZone $timeZone = null): DateTime
533
    {
534 1015
        $dtobj = DateTime::createFromFormat('U', $date) ?: new DateTime();
535 1015
        $dtobj->setTimeZone($timeZone ?? self::getDefaultOrLocalTimezone());
536
537 1015
        return $dtobj;
538
    }
539
540 10
    public static function formattedDateTimeFromTimestamp(string $date, string $format, ?DateTimeZone $timeZone = null): string
541
    {
542 10
        $dtobj = self::dateTimeFromTimestamp($date, $timeZone);
543
544 10
        return $dtobj->format($format);
545
    }
546
547
    /**
548
     * Round the given DateTime object to seconds.
549
     */
550 666
    public static function roundMicroseconds(DateTime $dti): void
551
    {
552 666
        $microseconds = (int) $dti->format('u');
553 666
        $rounded = (int) round($microseconds, -6);
554 666
        $modify = $rounded - $microseconds;
555 666
        if ($modify !== 0) {
556 23
            $dti->modify(($modify > 0 ? '+' : '') . $modify . ' microseconds');
557
        }
558
    }
559
}
560