• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPOffice / PhpSpreadsheet / 23381448657

21 Mar 2026 02:11PM UTC coverage: 96.879% (-0.03%) from 96.907%
23381448657

Pull #4841

github

web-flow
Merge 0f01633d0 into ff7ef51df
Pull Request #4841: Issue 4840

10 of 24 new or added lines in 1 file covered. (41.67%)

47746 of 49284 relevant lines covered (96.88%)

384.19 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.46
/src/PhpSpreadsheet/Shared/Date.php
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
use Throwable;
15

16
class Date
17
{
18
    /** constants */
19
    const CALENDAR_WINDOWS_1900 = 1900; //    Base date of 1st Jan 1900 = 1.0
20
    const CALENDAR_MAC_1904 = 1904; //    Base date of 2nd Jan 1904 = 1.0
21

22
    /**
23
     * Names of the months of the year, indexed by shortname
24
     * Planned usage for locale settings.
25
     *
26
     * @var string[]
27
     */
28
    public static array $monthNames = [
29
        'Jan' => 'January',
30
        'Feb' => 'February',
31
        'Mar' => 'March',
32
        'Apr' => 'April',
33
        'May' => 'May',
34
        'Jun' => 'June',
35
        'Jul' => 'July',
36
        'Aug' => 'August',
37
        'Sep' => 'September',
38
        'Oct' => 'October',
39
        'Nov' => 'November',
40
        'Dec' => 'December',
41
    ];
42

43
    /**
44
     * @var string[]
45
     */
46
    public static array $numberSuffixes = [
47
        'st',
48
        'nd',
49
        'rd',
50
        'th',
51
    ];
52

53
    /**
54
     * Base calendar year to use for calculations
55
     * Value is either CALENDAR_WINDOWS_1900 (1900) or CALENDAR_MAC_1904 (1904).
56
     */
57
    protected static int $excelCalendar = self::CALENDAR_WINDOWS_1900;
58

59
    /**
60
     * Default timezone to use for DateTime objects.
61
     */
62
    protected static ?DateTimeZone $defaultTimeZone = null;
63

64
    /**
65
     * Set the Excel calendar (Windows 1900 or Mac 1904).
66
     *
67
     * @param ?int $baseYear Excel base date (1900 or 1904)
68
     *
69
     * @return bool Success or failure
70
     */
71
    public static function setExcelCalendar(?int $baseYear): bool
10,153✔
72
    {
73
        if (
74
            ($baseYear === self::CALENDAR_WINDOWS_1900)
10,153✔
75
            || ($baseYear === self::CALENDAR_MAC_1904)
10,153✔
76
        ) {
77
            self::$excelCalendar = $baseYear;
10,153✔
78

79
            return true;
10,153✔
80
        }
81

82
        return false;
1✔
83
    }
84

85
    /**
86
     * Return the Excel calendar (Windows 1900 or Mac 1904).
87
     *
88
     * @return int Excel base date (1900 or 1904)
89
     */
90
    public static function getExcelCalendar(): int
10,567✔
91
    {
92
        return self::$excelCalendar;
10,567✔
93
    }
94

95
    /**
96
     * Set the Default timezone to use for dates.
97
     *
98
     * @param null|DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions
99
     *
100
     * @return bool Success or failure
101
     */
102
    public static function setDefaultTimezone($timeZone): bool
149✔
103
    {
104
        try {
105
            $timeZone = self::validateTimeZone($timeZone);
149✔
106
            self::$defaultTimeZone = $timeZone;
149✔
107
            $retval = true;
149✔
108
        } catch (PhpSpreadsheetException) {
1✔
109
            $retval = false;
1✔
110
        }
111

112
        return $retval;
149✔
113
    }
114

115
    /**
116
     * Return the Default timezone, or UTC if default not set.
117
     */
118
    public static function getDefaultTimezone(): DateTimeZone
2,624✔
119
    {
120
        return self::$defaultTimeZone ?? new DateTimeZone('UTC');
2,624✔
121
    }
122

123
    /**
124
     * Return the Default timezone, or local timezone if default is not set.
125
     */
126
    public static function getDefaultOrLocalTimezone(): DateTimeZone
1,150✔
127
    {
128
        return self::$defaultTimeZone ?? new DateTimeZone(date_default_timezone_get());
1,150✔
129
    }
130

131
    /**
132
     * Return the Default timezone even if null.
133
     */
134
    public static function getDefaultTimezoneOrNull(): ?DateTimeZone
149✔
135
    {
136
        return self::$defaultTimeZone;
149✔
137
    }
138

139
    /**
140
     * Validate a timezone.
141
     *
142
     * @param null|DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object
143
     *
144
     * @return ?DateTimeZone The timezone as a timezone object
145
     */
146
    private static function validateTimeZone($timeZone): ?DateTimeZone
168✔
147
    {
148
        if ($timeZone instanceof DateTimeZone || $timeZone === null) {
168✔
149
            return $timeZone;
168✔
150
        }
151
        if (in_array($timeZone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC))) {
26✔
152
            return new DateTimeZone($timeZone);
25✔
153
        }
154

155
        throw new PhpSpreadsheetException('Invalid timezone');
1✔
156
    }
157

158
    /**
159
     * @param mixed $value Converts a date/time in ISO-8601 standard format date string to an Excel
160
     *                         serialized timestamp.
161
     *                     See https://en.wikipedia.org/wiki/ISO_8601 for details of the ISO-8601 standard format.
162
     */
163
    public static function convertIsoDate(mixed $value): float|int
28✔
164
    {
165
        if (!is_string($value)) {
28✔
166
            throw new Exception('Non-string value supplied for Iso Date conversion');
1✔
167
        }
168

169
        $date = new DateTime($value);
27✔
170
        $dateErrors = DateTime::getLastErrors();
27✔
171

172
        if (is_array($dateErrors) && ($dateErrors['warning_count'] > 0 || $dateErrors['error_count'] > 0)) {
27✔
173
            throw new Exception("Invalid string $value supplied for datatype Date");
1✔
174
        }
175

176
        $newValue = self::dateTimeToExcel($date);
26✔
177

178
        if (preg_match('/^\s*\d?\d:\d\d(:\d\d([.]\d+)?)?\s*(am|pm)?\s*$/i', $value) == 1) {
26✔
179
            $newValue = fmod($newValue, 1.0);
4✔
180
        }
181

182
        return $newValue;
26✔
183
    }
184

185
    /**
186
     * Convert a MS serialized datetime value from Excel to a PHP Date/Time object.
187
     *
188
     * @param float|int $excelTimestamp MS Excel serialized date/time value
189
     * @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp,
190
     *                                           if you don't want to treat it as a UTC value
191
     *                                           Use the default (UTC) unless you absolutely need a conversion
192
     *
193
     * @throws \Exception
194
     *
195
     * @return DateTime PHP date/time object
196
     */
197
    public static function excelToDateTimeObject(float|int $excelTimestamp, null|DateTimeZone|string $timeZone = null): DateTime
2,662✔
198
    {
199
        $timeZone = ($timeZone === null) ? self::getDefaultTimezone() : self::validateTimeZone($timeZone);
2,662✔
200
        if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) {
2,662✔
201
            if ($excelTimestamp < 1 && self::$excelCalendar === self::CALENDAR_WINDOWS_1900) {
2,638✔
202
                // Unix timestamp base date
203
                $baseDate = new DateTime('1970-01-01', $timeZone);
208✔
204
            } else {
205
                // MS Excel calendar base dates
206
                if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) {
2,490✔
207
                    // Allow adjustment for 1900 Leap Year in MS Excel
208
                    $baseDate = ($excelTimestamp < 60) ? new DateTime('1899-12-31', $timeZone) : new DateTime('1899-12-30', $timeZone);
2,392✔
209
                } else {
210
                    $baseDate = new DateTime('1904-01-01', $timeZone);
100✔
211
                }
212
            }
213
        } else {
214
            $baseDate = new DateTime('1899-12-30', $timeZone);
24✔
215
        }
216

217
        if (is_int($excelTimestamp)) {
2,662✔
218
            if ($excelTimestamp >= 0) {
174✔
219
                return self::safeModify($baseDate, "+ $excelTimestamp days");
174✔
220
            }
221

222
            return self::safeModify($baseDate, "$excelTimestamp days");
1✔
223
        }
224
        $days = floor($excelTimestamp);
2,564✔
225
        $partDay = $excelTimestamp - $days;
2,564✔
226
        $hms = 86400 * $partDay;
2,564✔
227
        $microseconds = (int) round(fmod($hms, 1) * 1000000);
2,564✔
228
        $hms = (int) floor($hms);
2,564✔
229
        $hours = intdiv($hms, 3600);
2,564✔
230
        $hms -= $hours * 3600;
2,564✔
231
        $minutes = intdiv($hms, 60);
2,564✔
232
        $seconds = $hms % 60;
2,564✔
233

234
        if ($days >= 0) {
2,564✔
235
            $days = '+' . $days;
2,559✔
236
        }
237
        $interval = $days . ' days';
2,564✔
238

239
        return self::safeModify($baseDate, $interval)
2,564✔
240
            ->setTime($hours, $minutes, $seconds, $microseconds);
2,564✔
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
    public static function excelToTimestamp($excelTimestamp, $timeZone = null): int
55✔
256
    {
257
        $dto = self::excelToDateTimeObject($excelTimestamp, $timeZone);
55✔
258
        self::roundMicroseconds($dto);
55✔
259

260
        return (int) $dto->format('U');
55✔
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
    public static function PHPToExcel(mixed $dateValue)
288✔
273
    {
274
        if ((is_object($dateValue)) && ($dateValue instanceof DateTimeInterface)) {
288✔
275
            return self::dateTimeToExcel($dateValue);
283✔
276
        } elseif (is_numeric($dateValue)) {
6✔
277
            return self::timestampToExcel($dateValue);
4✔
278
        } elseif (is_string($dateValue)) {
2✔
279
            return self::stringToExcel($dateValue);
1✔
280
        }
281

282
        return false;
1✔
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
    public static function dateTimeToExcel(DateTimeInterface $dateValue): float
358✔
293
    {
294
        $seconds = (float) sprintf('%d.%06d', $dateValue->format('s'), $dateValue->format('u'));
358✔
295

296
        return self::formattedPHPToExcel(
358✔
297
            (int) $dateValue->format('Y'),
358✔
298
            (int) $dateValue->format('m'),
358✔
299
            (int) $dateValue->format('d'),
358✔
300
            (int) $dateValue->format('H'),
358✔
301
            (int) $dateValue->format('i'),
358✔
302
            $seconds
358✔
303
        );
358✔
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
    public static function timestampToExcel($unixTimestamp): bool|float
22✔
316
    {
317
        if (!is_numeric($unixTimestamp)) {
22✔
318
            return false;
1✔
319
        }
320

321
        return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp));
21✔
322
    }
323

324
    /**
325
     * formattedPHPToExcel.
326
     *
327
     * @return float Excel date/time value
328
     */
329
    public static function formattedPHPToExcel(int $year, int $month, int $day, int $hours = 0, int $minutes = 0, float|int $seconds = 0): float
2,784✔
330
    {
331
        if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) {
2,784✔
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
            $excel1900isLeapYear = true;
2,713✔
337
            if (($year == 1900) && ($month <= 2)) {
2,713✔
338
                $excel1900isLeapYear = false;
254✔
339
            }
340
            $myexcelBaseDate = 2415020;
2,713✔
341
        } else {
342
            $myexcelBaseDate = 2416481;
73✔
343
            $excel1900isLeapYear = false;
73✔
344
        }
345

346
        //    Julian base date Adjustment
347
        if ($month > 2) {
2,784✔
348
            $month -= 3;
1,840✔
349
        } else {
350
            $month += 9;
1,769✔
351
            --$year;
1,769✔
352
        }
353

354
        //    Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
355
        $century = (int) substr((string) $year, 0, 2);
2,784✔
356
        $decade = (int) substr((string) $year, 2, 2);
2,784✔
357
        $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear;
2,784✔
358

359
        $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
2,784✔
360

361
        return (float) $excelDate + $excelTime;
2,784✔
362
    }
363

364
    /**
365
     * Is a given cell a date/time?
366
     */
367
    public static function isDateTime(Cell $cell, mixed $value = null, bool $dateWithoutTimeOkay = true): bool
21✔
368
    {
369
        $result = false;
21✔
370
        $worksheet = $cell->getWorksheetOrNull();
21✔
371
        $spreadsheet = ($worksheet === null) ? null : $worksheet->getParent();
21✔
372
        if ($worksheet !== null && $spreadsheet !== null) {
21✔
373
            $index = $spreadsheet->getActiveSheetIndex();
21✔
374
            $selected = $worksheet->getSelectedCells();
21✔
375

376
            try {
377
                if ($value === null) {
21✔
378
                    $value = Functions::flattenSingleValue(
13✔
379
                        $cell->getCalculatedValue()
13✔
380
                    );
13✔
381
                }
382
                if (is_numeric($value)) {
21✔
383
                    $result = self::isDateTimeFormat(
19✔
384
                        $worksheet->getStyle(
19✔
385
                            $cell->getCoordinate()
19✔
386
                        )->getNumberFormat(),
19✔
387
                        $dateWithoutTimeOkay
19✔
388
                    );
19✔
389
                    /** @var float|int $value */
390
                    self::excelToDateTimeObject($value);
21✔
391
                }
392
            } catch (Throwable) {
5✔
393
                $result = false;
5✔
394
            }
395
            $worksheet->setSelectedCells($selected);
21✔
396
            $spreadsheet->setActiveSheetIndex($index);
21✔
397
        }
398

399
        return $result;
21✔
400
    }
401

402
    /**
403
     * Is a given NumberFormat code a date/time format code?
404
     */
405
    public static function isDateTimeFormat(NumberFormat $excelFormatCode, bool $dateWithoutTimeOkay = true): bool
19✔
406
    {
407
        return self::isDateTimeFormatCode((string) $excelFormatCode->getFormatCode(), $dateWithoutTimeOkay);
19✔
408
    }
409

410
    private const POSSIBLE_DATETIME_FORMAT_CHARACTERS = 'eymdHs';
411
    private const POSSIBLE_TIME_FORMAT_CHARACTERS = 'Hs'; // note - no 'm' due to ambiguity
412

413
    /**
414
     * Is a given number format code a date/time?
415
     */
416
    public static function isDateTimeFormatCode(string $excelFormatCode, bool $dateWithoutTimeOkay = true): bool
147✔
417
    {
418
        if (strtolower($excelFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) {
147✔
419
            //    "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check)
420
            return false;
61✔
421
        }
422
        if (preg_match('/[0#]E[+-]0/i', $excelFormatCode)) {
96✔
423
            //    Scientific format
424
            return false;
1✔
425
        }
426

427
        // Switch on formatcode
428
        $excelFormatCode = (string) NumberFormat::convertSystemFormats($excelFormatCode);
96✔
429
        if (in_array($excelFormatCode, NumberFormat::DATE_TIME_OR_DATETIME_ARRAY, true)) {
96✔
430
            return $dateWithoutTimeOkay || in_array($excelFormatCode, NumberFormat::TIME_OR_DATETIME_ARRAY);
58✔
431
        }
432

433
        //    Typically number, currency or accounting (or occasionally fraction) formats
434
        if ((str_starts_with($excelFormatCode, '_')) || (str_starts_with($excelFormatCode, '0 '))) {
45✔
435
            return false;
1✔
436
        }
437
        // Some "special formats" provided in German Excel versions were detected as date time value,
438
        // so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany).
439
        if (str_contains($excelFormatCode, '-00000')) {
44✔
440
            return false;
2✔
441
        }
442
        $possibleFormatCharacters = $dateWithoutTimeOkay ? self::POSSIBLE_DATETIME_FORMAT_CHARACTERS : self::POSSIBLE_TIME_FORMAT_CHARACTERS;
42✔
443
        // Try checking for any of the date formatting characters that don't appear within square braces
444
        if (preg_match('/(^|])[^\[]*[' . $possibleFormatCharacters . ']/i', $excelFormatCode)) {
42✔
445
            //    We might also have a format mask containing quoted strings...
446
            //        we don't want to test for any of our characters within the quoted blocks
447
            if (str_contains($excelFormatCode, '"')) {
21✔
448
                $segMatcher = false;
7✔
449
                foreach (explode('"', $excelFormatCode) as $subVal) {
7✔
450
                    //    Only test in alternate array entries (the non-quoted blocks)
451
                    $segMatcher = $segMatcher === false;
7✔
452
                    if (
453
                        $segMatcher
7✔
454
                        && (preg_match('/(^|])[^\[]*[' . $possibleFormatCharacters . ']/i', $subVal))
7✔
455
                    ) {
456
                        return true;
6✔
457
                    }
458
                }
459

460
                return false;
1✔
461
            }
462

463
            return true;
19✔
464
        }
465

466
        // No date...
467
        return false;
28✔
468
    }
469

470
    /**
471
     * Convert a date/time string to Excel time.
472
     *
473
     * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10'
474
     *
475
     * @return false|float Excel date/time serial value
476
     */
477
    public static function stringToExcel(string $dateValue): bool|float
188✔
478
    {
479
        if (strlen($dateValue) < 2) {
188✔
480
            return false;
27✔
481
        }
482
        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}([.]\d+)?)?)?$/iu', $dateValue)) {
163✔
483
            return false;
156✔
484
        }
485

486
        $dateValueNew = DateTimeExcel\DateValue::fromString($dateValue);
13✔
487

488
        if (!is_float($dateValueNew)) {
13✔
489
            return false;
2✔
490
        }
491

492
        if (str_contains($dateValue, ':')) {
12✔
493
            $timeValue = DateTimeExcel\TimeValue::fromString($dateValue);
5✔
494
            if (!is_float($timeValue)) {
5✔
495
                return false;
1✔
496
            }
497
            $dateValueNew += $timeValue;
5✔
498
        }
499

500
        return $dateValueNew;
12✔
501
    }
502

503
    /**
504
     * Converts a month name (either a long or a short name) to a month number.
505
     *
506
     * @param string $monthName Month name or abbreviation
507
     *
508
     * @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name
509
     */
510
    public static function monthStringToNumber(string $monthName)
12✔
511
    {
512
        $monthIndex = 1;
12✔
513
        foreach (self::$monthNames as $shortMonthName => $longMonthName) {
12✔
514
            if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) {
12✔
515
                return $monthIndex;
6✔
516
            }
517
            ++$monthIndex;
12✔
518
        }
519

520
        return $monthName;
6✔
521
    }
522

523
    /**
524
     * Strips an ordinal from a numeric value.
525
     *
526
     * @param string $day Day number with an ordinal
527
     *
528
     * @return int|string The integer value with any ordinal stripped, or the original string argument if it isn't a valid numeric
529
     */
530
    public static function dayStringToNumber(string $day)
18✔
531
    {
532
        $strippedDayValue = (str_replace(self::$numberSuffixes, '', $day));
18✔
533
        if (is_numeric($strippedDayValue)) {
18✔
534
            return (int) $strippedDayValue;
15✔
535
        }
536

537
        return $day;
3✔
538
    }
539

540
    public static function dateTimeFromTimestamp(string $date, ?DateTimeZone $timeZone = null): DateTime
1,156✔
541
    {
542
        $dtobj = DateTime::createFromFormat('U', $date) ?: new DateTime();
1,156✔
543
        $dtobj->setTimeZone($timeZone ?? self::getDefaultOrLocalTimezone());
1,156✔
544

545
        return $dtobj;
1,156✔
546
    }
547

548
    public static function formattedDateTimeFromTimestamp(string $date, string $format, ?DateTimeZone $timeZone = null): string
10✔
549
    {
550
        $dtobj = self::dateTimeFromTimestamp($date, $timeZone);
10✔
551

552
        return $dtobj->format($format);
10✔
553
    }
554

555
    /**
556
     * Round the given DateTime object to seconds.
557
     */
558
    public static function roundMicroseconds(DateTime $dti): void
666✔
559
    {
560
        $microseconds = (int) $dti->format('u');
666✔
561
        $rounded = (int) round($microseconds, -6);
666✔
562
        $modify = $rounded - $microseconds;
666✔
563
        if ($modify !== 0) {
666✔
564
            self::safeModify($dti, ($modify > 0 ? '+' : '') . $modify . ' microseconds');
23✔
565
        }
566
    }
567

568
    /**
569
     * Safely modifies a DateTime object using a specified modification string.
570
     *
571
     * Prior to PHP 8.3, DateTime::modify() would return false on failure but would also
572
     * emit an E_WARNING. Starting with PHP 8.3, DateTime::modify() throws a DateMalformedStringException
573
     * on failure instead of returning false or emitting warnings.
574
     *
575
     * This method provides consistent exception-based error handling across PHP versions:
576
     * - For PHP 8.3+: Uses the native exception-throwing behavior of modify()
577
     * - For PHP < 8.3: Converts warnings to exceptions using a custom error handler
578
     *
579
     * This ensures that calling code can rely on exception handling for all date modification
580
     * failures regardless of the PHP version in use.
581
     *
582
     * @param DateTime $dateTime The DateTime object to be modified.
583
     * @param string $modifier A modification string, such as '+1 day', '-2 hours', 'last Monday', etc.
584
     *
585
     * @throws PhpSpreadsheetException If an error occurs during the date modification process.
586
     *
587
     * @return DateTime The modified DateTime object.
588
     */
589
    protected static function safeModify(DateTime $dateTime, string $modifier): DateTime
2,663✔
590
    {
591
        /**
592
         * Starting with PHP 8.3, DateTime::modify() throws a DateMalformedStringException on failure instead of
593
         * returning false or emitting warnings, so we don't need the error handler overhead and can just consume the
594
         * DateTime.modify() method.
595
         */
596
        if (PHP_VERSION_ID >= 80300) {
2,663✔
597
            return $dateTime->modify($modifier);
2,663✔
598
        }
599

NEW
600
        set_error_handler(
×
601
            /**
602
             * A selective error handler meant to capture E_WARNING such the following:
603
             *
604
             * > Warning: DateTime::modify(): Failed to parse time string (+ 3172011706730017 days)
605
             * > at position 0 (+): Unexpected character in
606
             * > […]/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php on line 220
607
             *
608
             * @param int $severity The severity level of the error.
609
             * @param string $message The error message to process.
610
             *
611
             * @throws PhpSpreadsheetException If the severity is E_WARNING and the message matches the specified
612
             *                                 condition.
613
             *
614
             * @return bool Returns false if the error is not of type E_WARNING or if the message does not match
615
             *              the specified condition. Throws PhpSpreadsheetException when conditions are met.
616
             */
NEW
617
            static function (int $severity, string $message): bool {
×
NEW
618
                if ($severity !== E_WARNING) {
×
NEW
619
                    return false;
×
620
                }
NEW
621
                if (!str_starts_with($message, 'DateTime::modify()')) {
×
NEW
622
                    return false;
×
623
                }
624

NEW
625
                throw new PhpSpreadsheetException($message);
×
NEW
626
            }
×
NEW
627
        );
×
628

629
        try {
NEW
630
            $result = $dateTime->modify($modifier);
×
NEW
631
            if ($result === false) {
×
NEW
632
                throw new PhpSpreadsheetException('Failed to modify date with interval: ' . $modifier);
×
633
            }
634

NEW
635
            return $result;
×
636
        } finally {
NEW
637
            restore_error_handler();
×
638
        }
639
    }
640
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc