Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamp to date in php and mongodb

Tags:

php

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);
like image 924
Keven Chantre Avatar asked Jan 20 '16 17:01

Keven Chantre


People also ask

How does MongoDB store dates in PHP?

I use the class MongoDate to create the date object: $today = new MongoDate(strtotime(date('Y-m-d 00:00:00'))); The problem is that once it is in my collection the date is 2 hours earlier. For instance, $today here should be 2013-05-28 00:00:00 but once in the database it is 2013-05-27 22:00:00 .

What is timestamp in MongoDB?

Timestamps. BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. This internal timestamp type is a 64 bit value where: the most significant 32 bits are a time_t value (seconds since the Unix epoch)

How to set date in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.


1 Answers

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);
like image 74
chridam Avatar answered Sep 30 '22 03:09

chridam