16

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.

5 Answers 5

33

$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);
Sign up to request clarification or add additional context in comments.

2 Comments

Not sure who's decision at 10Gen that was, but it is confusing. Shouldn't have to call the sec property. Ohh well.
that person actually has a handle here on StackOverflow: stackoverflow.com/users/4243/kristina
6

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(...)

Comments

2

you are missing the microsecond.

To show (mongo -> php)

$fecha = date(preg_replace('`(?<!\\\\)u`', $my_date->usec, 'Y-M-d H:i:s.u'), $my_date->sec);
//MongoDate ISODate("2013-05-28T15:27:24.735Z")
//Php Date 2013-May-28 10:27:24.735000

To send to mongo (php -> mongo)

$fecha_mongo = new MongoDate(strtotime($fecha));
//Fail function, the short way but, 70000 isn't equal to 700000.
//$fecha_mongo->usec = (int)$fecha_micro->format("u");
preg_match("/\.(.*)/", $fecha, $uSec);
$fecha_mongo->usec = (int)(count($uSec)==2?$uSec[1]:0);

//Php Date 2013-May-28 10:27:24.735000
//MongoDate ISODate("2013-05-28T15:27:24.735Z")

Good day!

Mario T.

Comments

1

Use MongoDB\BSON\UTCDateTime MongoDate is deprecated

$mongoDate = new \MongoDB\BSON\UTCDateTime(strtotime('2020-10-01 18:30:00'));

Comments

0

First, create date from millisecond using given function:

public function showdatefn($mili)
{   
    $seconds = (string)$mili / 1000;
    return date("d-m-Y", $seconds); 
}   
$date =$this->showdatefn(<put mongo date here>);

This will give you correct date.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.