3

I did the update from php 7.2 to 7.4 and I find an unexpected behavior when i store datetime in mongodb

so i try

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->needToBeDrop->datetime;

$document =[ 
    'name'=>'some date',
    'mongo_date'=> new MongoDB\BSON\UTCDateTime(new DateTime()),
    'date'=> new DateTime()
];
$result = $collection->insertOne($document);

in php 7.4 i have this result:

{
    "name": "some date 7.4",
    "mongo_date": {
        "$date": 1583845613778
    },
    "date": {}
}

and in php 7.2 i have

{
    "name": "some date 7.2",
    "mongo_date": {
        "$date": 1583845637335
    },
    "date": {
        "date": "2020-03-10 13:07:17.335813",
        "timezone_type": 3,
        "timezone": "UTC"
    }
}

how i can keep the php 7.2 behavior ?

Simon
  • 33
  • 2
  • 1
    The DateTime class hasn't changed at all after php7.2 release. Are you sure the setup of your infrastructure is the same? for example php extensions? – matiit Mar 10 '20 at 13:50
  • ok i have mongodb extension v 1.5.3 on php 7.2 and 1.7.3 for php 7.4 – Simon Mar 10 '20 at 13:58
  • Try `new MongoDB\BSON\UTCDateTime(NULL)` - that's how I create timestamp of now. – Wernfried Domscheit Mar 10 '20 at 19:01
  • 1
    Same problem here and since php 7.4 update date is also empty object, the thing is we need to have the previous date format and not the BSON UTCDateTime one... Did you find any solutions @Simon ?? Thanks – Laurie Clark May 15 '20 at 15:24

1 Answers1

3

The problem is related with DateTime object to json serialization. I've tried on PHP 7.4 :

$d = new \DateTime();
echo json_encode(d);

and result is:

{
   "date":"2020-08-14 14:33:33.910110",
   "timezone_type":3,
   "timezone":"UTC"
}

This is same with PHP 7.2 mongodb record. But mongodb extensiton on PHP 7.4 (my mongodb extensiton version is 1.6.1) is not correctly serializing DateTime object. I've refactored my code from

["datetime"=>new \DateTime()] 

to

["datetime"=>json_decode(json_encode(new \DateTime()),true)]

Then I tested with sort({"datetime":-1}) method and it's work!

I hope I could help

Ahmet Erkan ÇELİK
  • 2,364
  • 1
  • 26
  • 28