我发现 UTCDateTime 对象有些奇怪:
$dt = new UTCDateTime(time());
var_dump($dt);
输出:
object(MongoDB\BSON\UTCDateTime)#208 (1) {
["milliseconds"]=>
int(1478644003)
}
好的,所以这个时间戳是 2016 年 11 月 8 日。
但是当我执行以下操作时:
var_dump($dt->toDateTime());
输出:
object(DateTime)#206 (3) {
["date"]=>
string(26) "1970-01-18 02:44:04.105000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+00:00"
}
日期重置为 1970 :( 这可能是什么原因?我是否正确使用了这些对象?它应该是 UTCDateTime 的 DateTime 表示 - http://php.net/manual/en/mongodb-bson-utcdatetime.todatetime.php
最佳答案
为您的代码选择任一步骤
第 1 步:
new MongoDB\BSON\UTCDateTime( (int) $timestamp * 1000 );
第 2 步:
您可以使用下面的函数而不是直接赋值。示例:mongoDate('1542957787');
function mongoDate( $timestamp = '' ) {
if ( empty($timestamp) && $timestamp != 0 ) {
return false;
}
if ( strlen( (string) $timestamp ) == 13 ) { // timestamp length in MilliSeconds
return new MongoDB\BSON\UTCDateTime( (int) $timestamp );
}
return new MongoDB\BSON\UTCDateTime( (int) $timestamp * 1000 );
}
关于php - UTCDateTime::toDateTime() 方法返回 1970 日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40497558/