2016-01-20 126 views
7

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

的代码是:

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

    $datetime = $utcdatetime->toDateTime(); 

    var_dump($datetime); 

回答

11

documentation状态,构造函数取入表示以毫秒为单位的时间戳记的整数参数,则所提供的,因此秒无效的日期结果的时间戳。

乘以1000的值来获得以毫秒为单位的时间戳从而返回转化为有效的datetime对象:

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

$datetime = $utcdatetime->toDateTime(); 

var_dump($datetime); 
+0

嗨chridam,谢谢你的答案,但现在我得到1969-12-08 05:14:47作为日期。任何想法为什么? –

+2

这听起来像是在运行一个32位版本的PHP,它无法处理像毫秒级时间戳那样大的数字。除了运行64位PHP之外,没有任何解决方法,或者完全不使用此Mongo对象,因为您显然需要DateTime。 '$ foo = new DateTime(); $ foo->的setTimestamp(1453939200); var_dump($ foo);' – Sammitch

+0

会同意@Sammitch在这里 – chridam

0

为了任何人寻找这样的: 你必须先将该值转换的时间戳和之后您将能够在有效的ISODate中进行转换。 例如:

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

UTCDateTime将基于毫秒的时间戳作为参数,strtotime返回基于秒的时间戳。 http://php.net/manual/en/class.mongodb-bson-utcdatetime.php – Weboide