【问题标题】:Timestamp to date in php and mongodbphp 和 mongodb 中的时间戳
【发布时间】:2017-11-08 10:09:23
【问题描述】:

我花了 3 天时间试图解决这个问题,但没有成功。 我正在使用 MongoDB PHP 库,我正在尝试使用 PHP Docs 中的示例将时间戳转换为有效日期,但它始终返回 1970-01-17。

代码是:

  $utcdatetime = new MongoDB\BSON\UTCDateTime(1453939200);

  $datetime = $utcdatetime->toDateTime();

  var_dump($datetime);

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    documentation 声明构造函数接受一个整数参数,表示以毫秒为单位的时间戳,您提供的时间戳以秒为单位,因此日期结果无效。

    将该值乘以 1000 得到时间戳(以毫秒为单位),从而返回转换后的有效日期时间对象:

    $timestamp = 1453939200 * 1000;
    $utcdatetime = new MongoDB\BSON\UTCDateTime($timestamp);
    
    $datetime = $utcdatetime->toDateTime();
    
    var_dump($datetime);
    

    【讨论】:

    • 嗨,chridam,感谢您的回答,但现在我的日期是 1969-12-08 05:14:47。知道为什么吗?
    • 听起来您正在运行一个 32 位版本的 PHP,它无法处理以毫秒为单位的时间戳那么大的数字。除了运行 64 位 PHP 或根本不使用这个 Mongo 对象之外,没有任何解决方法,因为您显然想要一个 DateTime。 $foo = new DateTime(); $foo->setTimestamp(1453939200); var_dump($foo);
    • 会同意@Sammitch 的观点
    • 再次感谢各位。 @Sammitch,phpinfo 告诉我我使用的是 64 位版本的 PHP。我可以将 1453939200 * 1000 的结果显示为浮点数。我想使用 mongo 对象,因为我会将这些数据插入到数据库中。使用 DateTime,日期被保存为日期、timezone_type 和 timezone 的数组,而不仅仅是 mongo 中的日期对象。可能问题出在 php-mongo 的驱动程序和/或库中。
    【解决方案2】:

    致任何寻找这个的人: 您必须首先将值转换为时间戳,然后才能将其转换为有效的 ISODate。 例如:

      $utcdatetime = new MongoDB\BSON\UTCDateTime(strtotime($date));
      $date2 = new MongoDB\BSON\Timestamp(1, date($utcdatetime));
    

    【讨论】:

    猜你喜欢
    • 2017-07-01
    • 2012-10-01
    • 2014-04-14
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    相关资源
    最近更新 更多