2024 年日本 PHP 研討會

MongoDB\BSON\UTCDateTime 類別

(mongodb >=1.0.0)

簡介

表示 » BSON 日期。此值是一個 64 位元整數,表示自 Unix 紀元 (1970 年 1 月 1 日) 以來的毫秒數。負值表示 1970 年之前的日期。

類別概要

final class MongoDB\BSON\UTCDateTime implements MongoDB\BSON\UTCDateTimeInterface, MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final public jsonSerialize(): mixed
final public serialize(): string
final public toDateTime(): DateTime
final public __toString(): string
final public unserialize(string $data): void
}

更新日誌

版本 說明
PECL mongodb 1.12.0 在 PHP 8.0+ 中實作 Stringable 介面。
PECL mongodb 1.3.0 實作 MongoDB\BSON\UTCDateTimeInterface 介面。
PECL mongodb 1.2.0 實作 SerializableJsonSerializable 介面。

目錄

新增註記

使用者貢獻的註記 3 則註記

Stephen
6 年前
使用 MongoDB\BSON\UTCDateTime 進行查詢時,請確保 strtotime 的實例使用毫秒作為建構函式的參數。

$start = new MongoDB\BSON\UTCDateTime(strtotime("midnight") * 1000);
$filter = ['date' => ['$gte' => $start]];
$options = ['sort' => ['date' => -1]];
$query = new MongoDB\Driver\Query($filter, $options);
mark at DONTSPAM dot moderndeveloperllc dot com
8 年前
如果您需要微秒精度,使用 UTCDateTime 時要小心,因為這個類別只儲存到 _毫秒_。如果您想要完整的精度,您需要將日期以字串形式儲存在 MongoDB 中。將 DateTime 轉換為浮點數也可能會降低精度。

一個簡單的查看差異的方法是:

程式碼
var_dump(
(new DateTime)->format('U.u'),
(float) (new DateTime)->format('U.u'),
(new MongoDB\BSON\UTCDateTime())->toDateTime()->format('U.u')
);

輸出
string(17) "1477534060.918415"
double(1477534060.9185)
string(17) "1477534060.918000"

注意:許多關於 DateTimeInterface 類別的微秒格式化錯誤已在 PHP 7.1.0 RC4 中修復。以上程式碼來自 PHP 7.1.0 RC5 和 mongodb 1.2.0alpha3。1.2.0 版本的擴充程式增加了在不傳入整數毫秒的情況下實例化此類別的功能。
mike at brenden dot com
6 年前
來源 [網址]https://github.com/mongodb/mongo-php-driver/issues/187[/url]

MichaelBrenden --

這兩個 Mongo 驅動程式如何判斷它們是否可以將某些內容轉換為 ISODate 格式?

mongo.so 是否需要 MongoDate 的類別型別,還是它是由 __toString() 返回的資料決定的(例如「0.12345678 1234567890」)?

mongodb.so 是否需要 \MongoDB\BSON\UTCDateTime 的類別型別,還是它是由 __toString() 返回的資料決定的(例如「1234567890123」)?

jmikola --

>> ISODate 格式?

記錄一下,ISODate 只是 mongo shell 中的一個輔助函式。實際的 BSON 類型在 BSON 規範中是 0x09,最好稱為「UTC 日期時間」。
[網址]https://docs.mongodb.com/manual/core/shell-types/#return-date[/url]
[網址]http://bsonspec.org/spec.html[/url]

>> mongodb.so 是否需要 \MongoDB\BSON\UTCDateTime 的類別型別,還是它是由 __toString() 返回的資料決定的(例如「1234567890123」)?

驅動程式需要一個 MongoDB\BSON\UTCDateTime 物件才能編碼 BSON 日期類型。如果您想查看,BSON 編碼期間相關的 instanceof 檢查在這裡。__toString() 函式純粹是為了方便使用者應用程式而存在。驅動程式在測試之外不會使用它。
[網址]https://github.com/mongodb/mongo-php-driver/blob/1.3.4/src/bson-encode.c#L215[/url]

舊版 mongo.so 驅動程式也類似,它需要一個 MongoDate 物件才能編碼 BSON 日期類型(相關程式碼在這裡)。
[網址]https://github.com/mongodb/mongo-php-driver-legacy/blob/1.6.16/bson.c#L273[/url]
To Top