sec = (int) $sec; $this->usec = (int) $this->truncateMicroSeconds($usec); } /** * Returns a string representation of this date * @return string */ public function __toString() { return (string) sprintf('%.8f', $this->truncateMicroSeconds($this->usec) / 1000000) . ' ' . $this->sec; } /** * Converts this MongoDate to the new BSON UTCDateTime type * * @return UTCDateTime * @internal This method is not part of the ext-mongo API */ public function toBSONType() { $milliSeconds = ($this->sec * 1000) + ($this->truncateMicroSeconds($this->usec) / 1000); return new UTCDateTime($milliSeconds); } /** * Returns a DateTime object representing this date * @link http://php.net/manual/en/mongodate.todatetime.php * @return DateTime */ public function toDateTime() { $datetime = new \DateTime(); $datetime->setTimestamp($this->sec); $microSeconds = $this->truncateMicroSeconds($this->usec); if ($microSeconds > 0) { $datetime = \DateTime::createFromFormat('Y-m-d H:i:s.u', $datetime->format('Y-m-d H:i:s') . '.' . str_pad($microSeconds, 6, '0', STR_PAD_LEFT)); } $datetime->setTimezone(new \DateTimeZone("UTC")); return $datetime; } /** * @param int $usec * @return int */ private function truncateMicroSeconds($usec) { return (int) floor($usec / 1000) * 1000; } }