8

I spent 3 days trying to solve this with no success. I'm using the MongoDB PHP Library and i'm trying to convert a timestamp in a valid date using the example in the PHP Docs but it's always returning 1970-01-17.

The code is:

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

  $datetime = $utcdatetime->toDateTime();

  var_dump($datetime);

2 Answers 2

14

The documentation states that the constructor takes in an integer parameter representing the timestamp in milliseconds, you are providing a timestamp in seconds hence the invalid date result.

Multiply the value by 1000 to get the timestamp in milliseconds thus return a valid datetime object converted:

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

$datetime = $utcdatetime->toDateTime();

var_dump($datetime);
Sign up to request clarification or add additional context in comments.

4 Comments

Hi chridam, thanks for the answer but now i'm getting 1969-12-08 05:14:47 as date. Any idea why?
It sounds like you're running a 32-bit version of PHP that can't handle numbers as large as a timestamp in milliseconds. There is no workaround for this aside from either running 64-bit PHP, or not using this Mongo object at all since you apparently want a DateTime. $foo = new DateTime(); $foo->setTimestamp(1453939200); var_dump($foo);
Would agree with @Sammitch here on this one
Thanks again guys. @Sammitch, phpinfo is telling me i'm using a 64-bit version of PHP. I can show the result of 1453939200 * 1000 as float. I want to use the mongo object because i will insert this data in a database. Using DateTime, the date is saved as a array of date, timezone_type and timezone instead of just a date object in mongo. Probably the problem is in the driver and/or library of php-mongo.
0

To anyone looking for this: You have first to convert the value in a timestamp and after that you will be able to convert it in a valid ISODate. Eg:

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

1 Comment

UTCDateTime takes a millisecond-based timestamp as parameter, strtotime returns a second-based timestamp. php.net/manual/en/class.mongodb-bson-utcdatetime.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.