Skip to content

Commit fd96566

Browse files
authored
Merge pull request #4150 from marc-mabe/fix-Date-roundMicroseconds
Fix Date::roundMicroseconds() not resetting microsecond part
2 parents 5c931e9 + cd8e837 commit fd96566

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/PhpSpreadsheet/Shared/Date.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -537,11 +537,16 @@ public static function formattedDateTimeFromTimestamp(string $date, string $form
537537
return $dtobj->format($format);
538538
}
539539

540+
/**
541+
* Round the given DateTime object to seconds.
542+
*/
540543
public static function roundMicroseconds(DateTime $dti): void
541544
{
542545
$microseconds = (int) $dti->format('u');
543-
if ($microseconds >= 500000) {
544-
$dti->modify('+1 second');
546+
$rounded = (int) round($microseconds, -6);
547+
$modify = $rounded - $microseconds;
548+
if ($modify !== 0) {
549+
$dti->modify(($modify > 0 ? '+' : '') . $modify . ' microseconds');
545550
}
546551
}
547552
}

tests/PhpSpreadsheetTests/Shared/DateTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace PhpOffice\PhpSpreadsheetTests\Shared;
66

7+
use DateTime;
78
use DateTimeInterface;
89
use DateTimeZone;
910
use PhpOffice\PhpSpreadsheet\Exception;
@@ -249,4 +250,19 @@ public function testVarious(): void
249250
->setFormatCode('yyyy-mm-dd');
250251
self::assertFalse(Date::isDateTime($cella4));
251252
}
253+
254+
public function testRoundMicroseconds(): void
255+
{
256+
$dti = new DateTime('2000-01-02 03:04:05.999999');
257+
Date::roundMicroseconds($dti);
258+
self::assertEquals(new DateTime('2000-01-02 03:04:06.000000'), $dti);
259+
260+
$dti = new DateTime('2000-01-02 03:04:05.500000');
261+
Date::roundMicroseconds($dti);
262+
self::assertEquals(new DateTime('2000-01-02 03:04:06.000000'), $dti);
263+
264+
$dti = new DateTime('2000-01-02 03:04:05.499999');
265+
Date::roundMicroseconds($dti);
266+
self::assertEquals(new DateTime('2000-01-02 03:04:05.000000'), $dti);
267+
}
252268
}

0 commit comments

Comments
 (0)