The MongoDB\BSON\UTCDateTime class

(mongodb >=1.0.0)

Introduction

Represents a » BSON date. The value is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). Negative values represent dates before 1970.

Class synopsis

final class MongoDB\BSON\UTCDateTime implements MongoDB\BSON\UTCDateTimeInterface, MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final public jsonSerialize(): mixed
final public toDateTime(): DateTime
final public __toString(): string
}

Changelog

Version Description
PECL mongodb 2.0.0

This class no longer implements the Serializable interface.

PECL mongodb 1.12.0 Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 Implements MongoDB\BSON\UTCDateTimeInterface.
PECL mongodb 1.2.0 Implements Serializable and JsonSerializable.

Table of Contents

add a note

User Contributed Notes 3 notes

up
23
Stephen
6 years ago
When using MongoDB\BSON\UTCDateTime to query be sure for instances of strtotime you are putting the constructor in milliseconds:

$start = new MongoDB\BSON\UTCDateTime(strtotime("midnight") * 1000);
$filter = ['date' => ['$gte' => $start]];
$options = ['sort' => ['date' => -1]];
$query = new MongoDB\Driver\Query($filter,$options);
up
8
mark at DONTSPAM dot moderndeveloperllc dot com
8 years ago
Be careful using UTCDateTime if you need microsecond precision as this class only stores time to the _millisecond_. You need to store the date as a string in MongoDB if you want the full precision. Casting DateTime to a float can also remove precision.

An easy way to see the differences is with:

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

Output:
string(17) "1477534060.918415"
double(1477534060.9185)
string(17) "1477534060.918000"

NOTE: Lots of bugs concerning microsecond formatting for DateTimeInterface classes were fixed as of PHP 7.1.0 RC4. The above code is from PHP 7.1.0 RC5 and mongodb 1.2.0alpha3. The 1.2.0 version of the extension added the ability to instantiate this class without passing integer milliseconds.
up
1
mike at brenden dot com
7 years ago
SOURCE [url]https://github.com/mongodb/mongo-php-driver/blob/1.3.4/src/bson-encode.c#L215[/url]

The legacy mongo.so driver is similar in that it requires a MongoDate object in order to encode a BSON date type (relevant code is here).
[url]https://github.com/mongodb/mongo-php-driver-legacy/blob/1.6.16/bson.c#L273[/url]
To Top

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant