Keven Chantre
Keven Chantre

Reputation: 89

Timestamp to date in php and mongodb

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);

Upvotes: 8

Views: 17071

Answers (2)

Keven Chantre
Keven Chantre

Reputation: 89

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));

Upvotes: 0

chridam
chridam

Reputation: 103305

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);

Upvotes: 14

Related Questions