Skip to content

Commit 58ade22

Browse files
committed
Fix Date::roundMicroseconds() not resetting microsecond part
1 parent e1dae99 commit 58ade22

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-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: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,4 +249,19 @@ public function testVarious(): void
249249
->setFormatCode('yyyy-mm-dd');
250250
self::assertFalse(Date::isDateTime($cella4));
251251
}
252+
253+
public function testRoundMicroseconds(): void
254+
{
255+
$dti = new \DateTime('2000-01-02 03:04:05.999999');
256+
Date::roundMicroseconds($dti);
257+
static::assertEquals(new \DateTime('2000-01-02 03:04:06.000000'), $dti);
258+
259+
$dti = new \DateTime('2000-01-02 03:04:05.500000');
260+
Date::roundMicroseconds($dti);
261+
static::assertEquals(new \DateTime('2000-01-02 03:04:06.000000'), $dti);
262+
263+
$dti = new \DateTime('2000-01-02 03:04:05.499999');
264+
Date::roundMicroseconds($dti);
265+
static::assertEquals(new \DateTime('2000-01-02 03:04:05.000000'), $dti);
266+
}
252267
}

0 commit comments

Comments
 (0)