How in PHP
do I get the regular timestamp format out of a MongoDB
date?
Assume I have:
$my_date;
print_r($my_date);
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(...)
Use MongoDB\BSON\UTCDateTime MongoDate is deprecated
$mongoDate = new \MongoDB\BSON\UTCDateTime(strtotime('2020-10-01 18:30:00'));
$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);
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.
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.