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.
$dt = new DateTime(date('Y-m-d'), new DateTimeZone('UTC')); $ts = $dt->getTimestamp(); $today = new MongoDate($ts); This is working. Save this answer.
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.
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.
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.
$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);
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(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With