Skip to content

Commit

Permalink
Fix Date::roundMicroseconds() not resetting microsecond part
Browse files Browse the repository at this point in the history
  • Loading branch information
marc-mabe committed Aug 26, 2024
1 parent e1dae99 commit cd8e837
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/PhpSpreadsheet/Shared/Date.php
Original file line number Diff line number Diff line change
Expand Up @@ -537,11 +537,16 @@ public static function formattedDateTimeFromTimestamp(string $date, string $form
return $dtobj->format($format);
}

/**
* Round the given DateTime object to seconds.
*/
public static function roundMicroseconds(DateTime $dti): void
{
$microseconds = (int) $dti->format('u');
if ($microseconds >= 500000) {
$dti->modify('+1 second');
$rounded = (int) round($microseconds, -6);
$modify = $rounded - $microseconds;
if ($modify !== 0) {
$dti->modify(($modify > 0 ? '+' : '') . $modify . ' microseconds');
}
}
}
16 changes: 16 additions & 0 deletions tests/PhpSpreadsheetTests/Shared/DateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace PhpOffice\PhpSpreadsheetTests\Shared;

use DateTime;
use DateTimeInterface;
use DateTimeZone;
use PhpOffice\PhpSpreadsheet\Exception;
Expand Down Expand Up @@ -249,4 +250,19 @@ public function testVarious(): void
->setFormatCode('yyyy-mm-dd');
self::assertFalse(Date::isDateTime($cella4));
}

public function testRoundMicroseconds(): void
{
$dti = new DateTime('2000-01-02 03:04:05.999999');
Date::roundMicroseconds($dti);
self::assertEquals(new DateTime('2000-01-02 03:04:06.000000'), $dti);

$dti = new DateTime('2000-01-02 03:04:05.500000');
Date::roundMicroseconds($dti);
self::assertEquals(new DateTime('2000-01-02 03:04:06.000000'), $dti);

$dti = new DateTime('2000-01-02 03:04:05.499999');
Date::roundMicroseconds($dti);
self::assertEquals(new DateTime('2000-01-02 03:04:05.000000'), $dti);
}
}

0 comments on commit cd8e837

Please sign in to comment.