Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

277
Visualizações
Storing and retrieving dates in Mongodb 3.2 with PHPLIB

Using Mongo and PHP how does one store a datetime type, and then retrieve by date?

This is what I have for inserting, but it stores the date as a string:

$collection->insertOne(['date_created' => '2017-01-02 17:20:15']);

How should I be sending the date to Mongo to store as a datetime type so I can do the proper finds?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Put an instance of this class into the array: http://php.net/manual/en/class.mongodb-bson-utcdatetime.php

You need to use the BSON objects in the PHP arrays: http://php.net/manual/en/book.bson.php

Those get serialized properly before passed to Mongo.

$test = array(  
    "_id" => 123, 
    "name" => "This is an example", 
    "date_created" => new MongoDB\BSON\UTCDateTime(time() * 1000)
);

$collection->insert($test);

The time() is multiplied by 1000, because the constructor wants the milliseconds elapsed since the unix epoch, and time() returns the seconds elapsed since the unix epoch. See: http://php.net/manual/en/mongodb-bson-utcdatetime.construct.php

UPDATE: To retrive the date/time in ISO format, just convert the UTCDateTime object fist to DateTime:

$date_created = $test["date_created"];
$iso_date = $date_created->toDateTime()->format("Y-m-d H:i:s");
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda