php - UTCDateTime::toDateTime() 方法返回 1970 日期时间

标签 php mongodb

我发现 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/

相关文章:

php - Centos : TERM environment Variable Not Set

PhP SQL注释系统

php - 从表中选择 1,奇怪的 print_r 结果

MongoDB 无法在 Karaf 4.0.8 和 Camel 2.18.1 上运行

mongodb - 将本地主机 MongoDB 数据复制到 meteor 服务器

security - 为什么不建议在 MongoDB 中使用服务器端存储函数?

php - MYSQL 5.6.12 中mysql插入查询出错

javascript - Ajax响应不带数据

Spring Data MongoDB : set repository collection?

node.js - NodeJS + Express 慢慢消耗越来越多的 CPU