Skip to content

Commit 47e92cd

Browse files
kindratmakccopybara-github
authored andcommitted
Fix inconsistent timestamp json encode/decode (#12396)
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
1 parent 8b4c7a1 commit 47e92cd

2 files changed

Lines changed: 14 additions & 0 deletions

File tree

php/src/Google/Protobuf/Internal/GPBUtil.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,10 @@ public static function parseTimestamp($timestamp)
462462
$nanoseconds = substr($timestamp, $periodIndex + 1, $nanosecondsLength);
463463
$nanoseconds = intval($nanoseconds);
464464

465+
if ($nanosecondsLength < 9) {
466+
$nanoseconds = $nanoseconds * pow(10, 9 - $nanosecondsLength);
467+
}
468+
465469
// remove the nanoseconds and preceding period from the timestamp
466470
$date = substr($timestamp, 0, $periodIndex);
467471
$timezone = substr($timestamp, $periodIndex + $nanosecondsLength + 1);

php/tests/EncodeDecodeTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -992,6 +992,16 @@ public function testEncodeTimestamp()
992992
$m->serializeToJsonString());
993993
}
994994

995+
public function testEncodeDecodeTimestampConsistency()
996+
{
997+
$m = new Google\Protobuf\Timestamp();
998+
$m->setSeconds(946684800);
999+
$m->setNanos(123000000);
1000+
$m->mergeFromJsonString($m->serializeToJsonString());
1001+
$this->assertEquals(946684800, $m->getSeconds());
1002+
$this->assertEquals(123000000, $m->getNanos());
1003+
}
1004+
9951005
public function testDecodeTopLevelValue()
9961006
{
9971007
$m = new Value();

0 commit comments

Comments
 (0)