Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

deekepMaks's avatar

Extract date from mongodb

I have a document like:

{
_id: ...
somekey: {
   date: 2023-07-04T13:46:06.008+00:00
}
created_at: 2023-07-04T13:46:06.008+00:00
}

I also have an array protected $dates = ['created_at', 'somekey.date']

Both dates are in the database are objects of the class MongoDB\BSON\UTCDateTime

When fetching data, I get dates like this:

somekey.date = "2023-07-04 13:46:06"
created_at = "2023-07-04T13:46:06.008000Z"

Why is one field returned with the time zone and the other is not? I need both fields to be returned in the format in which the field created_at is returned

The only difference is their retention somekey.date is stored with new UTCDateTime(Carbon::now()) and created_at is probably with Carbon::now()

I can't save somekey.date with Carbon::now() because I end up with an empty object in the database.

protected $dates doesn't help as it doesn't work when saving, but works when getting a date :)

0 likes
1 reply
deekepMaks's avatar

If it is a deep key, then the date is retrieved without the time zone

{
   "_id": "64a4303dd48877e74703af62",
   "test": {
      "date": "2023-07-04 14:44:13"
   },
   "updated_at": "2023-07-04T14:44:13.670000Z",
   "created_at": "2023-07-04T14:44:13.670000Z"
}

if the test itself contains a date, then everything is extracted correctly

{
   "_id": "64a430a7665e647a150c8ff2",
   "test": "2023-07-04T14:45:59.212000Z",
   "updated_at": "2023-07-04T14:45:59.224000Z",
   "created_at": "2023-07-04T14:45:59.224000Z"
}

how to solve this problem?

Please or to participate in this conversation.