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);
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 .
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)
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With