0

I have ISO dates stored in MongoDB.

> db.myDB.find()
{ "_id" : ObjectId("..."), "time" : ISODate("2014-08-05T11:18:55Z) }

When I echo it in PHP, it displays it differently from the database.

echo $document["time"] // Prints 0.00000000 1407236935

What's up with the zeros? What format is it printing it in? Is there a format I can use that will print more nicely, so a human could determine it with precision to the minute?

1

1 Answer 1

1

Date objects

The MongoDB PHP driver uses the MongoDate class to represent date objects.

If you inspect the contents of your variable with:

var_dump($document["time"])

... you'll see the internal class properties:

object(MongoDate)#7 (2) {
   ["sec"]=>
   int(1407299400)
   ["usec"]=>
   int(313000)
}

.. which, as you discovered, stringify to a pair of integers similar to microtime() if you try to echo() a MongoDate object:

0.31300000 1407299400

Formatting a MongoDate

To format as "human readable" you can pass the MongoDate value (in seconds) to the standard PHP date() function:

 echo date('F j, Y g:i a', $document["time"]->sec), "\n";

.. which should output similar to:

 August 6, 2014 2:30 pm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.