从 PHP 打印 MongoDB 日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12190136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing A MongoDB Date From PHP
提问by Justin
How in PHPdo I get the regular timestamp format out of a MongoDBdate?
如何PHP从MongoDB日期中获取常规时间戳格式?
Assume I have:
假设我有:
$my_date;
print_r($my_date);
The print_routput is:
该print_r输出是:
MongoDate Object ( [sec] => 1346300336 [usec] => 593000 )
But doing:
但是做:
echo $my_date;
Outputs:
输出:
0.59300000 1346300336
Even tried:
甚至尝试过:
echo (string)$my_date
Same thing.
一样。
回答by xdazz
$my_date->secis the unix timestamp, use date()function to show it in required format.
$my_date->sec是unix时间戳,使用date()函数以所需格式显示它。
echo date('Y-m-d H:i:s', $my_date->sec);
回答by haltabush
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 自 pecl 扩展的 1.6 版以来就有一个 toDateTime 方法。你现在可以做
$mongoDate->toDateTime()->format(...)
回答by mariofertc
you are missing the microsecond.
你错过了微秒。
To show (mongo -> php)
显示 (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)
发送到 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.
马里奥·T。
回答by manoj tiwari
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.
这将为您提供正确的日期。

