Skip to content

Commit

Permalink
Fix inconsistent timestamp json encode/decode (#12396)
Browse files Browse the repository at this point in the history
Protobuf php lib encodes 123_000_000 nano like this: 2000-01-01T00:00:00.**123**Z but then it gets decoded into 123 nanoseconds instead of 123_000_000.

There were issue opened some time ago that also describes this behaviour #4335

Closes #12396

COPYBARA_INTEGRATE_REVIEW=#12396 from kindratmakc:bugfix/inconsistent-timestamp-json-encode-decode df47c96
PiperOrigin-RevId: 603118615
  • Loading branch information
kindratmakc authored and Copybara-Service committed Jan 31, 2024
1 parent 8b4c7a1 commit 47e92cd
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
4 changes: 4 additions & 0 deletions php/src/Google/Protobuf/Internal/GPBUtil.php
Expand Up @@ -462,6 +462,10 @@ public static function parseTimestamp($timestamp)
$nanoseconds = substr($timestamp, $periodIndex + 1, $nanosecondsLength);
$nanoseconds = intval($nanoseconds);

if ($nanosecondsLength < 9) {
$nanoseconds = $nanoseconds * pow(10, 9 - $nanosecondsLength);
}

// remove the nanoseconds and preceding period from the timestamp
$date = substr($timestamp, 0, $periodIndex);
$timezone = substr($timestamp, $periodIndex + $nanosecondsLength + 1);
Expand Down
10 changes: 10 additions & 0 deletions php/tests/EncodeDecodeTest.php
Expand Up @@ -992,6 +992,16 @@ public function testEncodeTimestamp()
$m->serializeToJsonString());
}

public function testEncodeDecodeTimestampConsistency()
{
$m = new Google\Protobuf\Timestamp();
$m->setSeconds(946684800);
$m->setNanos(123000000);
$m->mergeFromJsonString($m->serializeToJsonString());
$this->assertEquals(946684800, $m->getSeconds());
$this->assertEquals(123000000, $m->getNanos());
}

public function testDecodeTopLevelValue()
{
$m = new Value();
Expand Down

0 comments on commit 47e92cd

Please sign in to comment.