以 php 和 mongodb 为单位的时间戳


Timestamp to date in php and mongodb

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

代码为:

  $utcdatetime = new MongoDB'BSON'UTCDateTime(1453939200);
  $datetime = $utcdatetime->toDateTime();
  var_dump($datetime);

文档指出,构造函数采用一个整数参数,该参数以毫秒为单位表示时间戳,您提供的时间戳(以秒为单位),因此日期结果无效。

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

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

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

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