function GPBUtil::parseTimestamp
2 calls to GPBUtil::parseTimestamp()
- Message::convertJsonValueToProtoValue in vendor/
google/ protobuf/ src/ Google/ Protobuf/ Internal/ Message.php - Message::mergeFromJsonArray in vendor/
google/ protobuf/ src/ Google/ Protobuf/ Internal/ Message.php
File
-
vendor/
google/ protobuf/ src/ Google/ Protobuf/ Internal/ GPBUtil.php, line 431
Class
Namespace
Google\Protobuf\InternalCode
public static function parseTimestamp($timestamp) {
// prevent parsing timestamps containing with the non-existent year "0000"
// DateTime::createFromFormat parses without failing but as a nonsensical date
if (substr($timestamp, 0, 4) === "0000") {
throw new \Exception("Year cannot be zero.");
}
// prevent parsing timestamps ending with a lowercase z
if (substr($timestamp, -1, 1) === "z") {
throw new \Exception("Timezone cannot be a lowercase z.");
}
$nanoseconds = 0;
$periodIndex = strpos($timestamp, ".");
if ($periodIndex !== false) {
$nanosecondsLength = 0;
// find the next non-numeric character in the timestamp to calculate
// the length of the nanoseconds text
for ($i = $periodIndex + 1, $length = strlen($timestamp); $i < $length; $i++) {
if (!is_numeric($timestamp[$i])) {
$nanosecondsLength = $i - ($periodIndex + 1);
break;
}
}
if ($nanosecondsLength % 3 !== 0) {
throw new \Exception("Nanoseconds must be disible by 3.");
}
if ($nanosecondsLength > 9) {
throw new \Exception("Nanoseconds must be in the range of 0 to 999,999,999 nanoseconds.");
}
if ($nanosecondsLength > 0) {
$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);
$timestamp = $date . $timezone;
}
}
$date = \DateTime::createFromFormat(\DateTime::RFC3339, $timestamp, new \DateTimeZone("UTC"));
if ($date === false) {
throw new \Exception("Invalid RFC 3339 timestamp.");
}
$value = new \Google\Protobuf\Timestamp();
$seconds = $date->format("U");
$value->setSeconds($seconds);
$value->setNanos($nanoseconds);
return $value;
}