Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing A MongoDB Date From PHP

Tags:

date

php

mongodb

How in PHP do I get the regular timestamp format out of a MongoDB date?

Assume I have:

$my_date;
print_r($my_date);

The print_r output is:

MongoDate Object ( [sec] => 1346300336 [usec] => 593000 )

But doing:

echo $my_date;

Outputs:

0.59300000 1346300336

Even tried:

echo (string)$my_date

Same thing.

like image 945
Justin Avatar asked Aug 30 '12 04:08

Justin


People also ask

How does MongoDB store dates in PHP?

$dt = new DateTime(date('Y-m-d'), new DateTimeZone('UTC')); $ts = $dt->getTimestamp(); $today = new MongoDate($ts); This is working. Save this answer.

How are dates written in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

Can I use PHP with MongoDB?

You can add the driver to your application to work with MongoDB in PHP. The MongoDB PHP Driver consists of the two following components: The extension , which provides a low-level API and mainly serves to integrate libmongoc and libbson with PHP.

Is there a date type in MongoDB?

The recommended way to store dates in MongoDB is to use the BSON Date data type. The BSON Specification refers to the Date type as the UTC datetime and is a 64-bit integer. It represents the number of milliseconds since the Unix epoch, which was 00:00:00 UTC on 1 January 1970.


2 Answers

$my_date->sec is the unix timestamp, use date() function to show it in required format.

echo date('Y-m-d H:i:s', $my_date->sec);
like image 137
xdazz Avatar answered Oct 12 '22 14:10

xdazz


Just a quick update, to say that MongoDate has a toDateTime method since the version 1.6 of the pecl extension. You can now do

$mongoDate->toDateTime()->format(...)
like image 26
haltabush Avatar answered Oct 12 '22 13:10

haltabush