Skip to content

Commit

Permalink
simplified datetime conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
transistive committed Mar 24, 2023
1 parent f4022af commit 6add25a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 24 deletions.
29 changes: 14 additions & 15 deletions src/Types/DateTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
use DateTimeZone;
use Exception;
use Laudis\Neo4j\Contracts\BoltConvertibleInterface;
use RuntimeException;

use function sprintf;

Expand Down Expand Up @@ -77,22 +76,22 @@ public function getTimeZoneOffsetSeconds(): int
*/
public function toDateTime(): DateTimeImmutable
{
/** @psalm-suppress all */
foreach (DateTimeZone::listAbbreviations() as $tz) {
/** @psalm-suppress all */
if ($tz[0]['offset'] === $this->getTimeZoneOffsetSeconds()) {
$dateTime = new DateTimeImmutable(sprintf('@%s', $this->getSeconds()));

if ($this->legacy) {
$dateTime = $dateTime->modify(sprintf('+%s microseconds', $this->nanoseconds / 1000));
}

return $dateTime->setTimezone(new DateTimeZone($tz[0]['timezone_id']));
}
$dateTime = new DateTimeImmutable(sprintf('@%s', $this->getSeconds()));
$dateTime = $dateTime->modify(sprintf('+%s microseconds', $this->nanoseconds / 1000));
/** @psalm-suppress PossiblyFalseReference */
$dateTime = $dateTime->setTimezone(new DateTimeZone(sprintf("%+'05d", $this->getTimeZoneOffsetSeconds() / 3600 * 100)));

if ($this->legacy) {
/**
* @psalm-suppress FalsableReturnStatement
*
* @var DateTimeImmutable
*/
return $dateTime->modify(sprintf('-%s seconds', $this->getTimeZoneOffsetSeconds()));
}

$message = sprintf('Cannot find an timezone with %s seconds as offset.', $this->tzOffsetSeconds);
throw new RuntimeException($message);
/** @var DateTimeImmutable */
return $dateTime;
}

/**
Expand Down
9 changes: 0 additions & 9 deletions tests/Integration/OGMFormatterIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -259,15 +259,6 @@ public function testDateTime(string $alias): void
} else {
self::assertEquals('{"seconds":1559410832,"nanoseconds":142000000,"tzOffsetSeconds":3600}', json_encode($createdAt, JSON_THROW_ON_ERROR));
}

self::assertInstanceOf(DateTime::class, $results[1]['created_at']);
self::assertEquals(1_559_471_012, $results[1]['created_at']->getSeconds());
self::assertEquals(122_000_000, $results[1]['created_at']->getNanoseconds());
self::assertEquals('{"seconds":1559471012,"nanoseconds":122000000,"tzOffsetSeconds":3600}', json_encode($results[1]['created_at'], JSON_THROW_ON_ERROR));

self::assertInstanceOf(DateTime::class, $results[2]['created_at']);
self::assertGreaterThan(0, $results[2]['created_at']->getSeconds());
self::assertGreaterThan(0, $results[2]['created_at']->getNanoseconds());
}

/**
Expand Down

0 comments on commit 6add25a

Please sign in to comment.