Reputation: 1630
I inserted data in MongoDB
via PHP
and one field is a date. So, according to the MongoDB documentation, I used a new MongoDate()
to do that.
In MongoDB, The date is stored such as ISODate("2013-07-03T22:56:12Z")
. That means my timezone is Z
(= 0Z
), so the timezone is equal to 0.
But I am in the US West coast and the timezone for my location is 8Z
(Pacific Time).
When I type new Date()
on Mongo in the terminal, everythin g is OK. The date is ISODate("2013-07-03T22:56:128Z")
, so this is the correct timezone 8Z
.
My development environment is Windows and MongoDB is version 2.4.4
Is there something to setup in MongoDB, in the PHP code or in the php.ini to avoid this error?
Upvotes: 2
Views: 5919
Reputation: 1552
The latest MongoDate class as a toDateTime() function which allows you to set timezone.
$mongoDate = new \MongoDate();
$dateTime = $mongoDate->toDateTime()->setTimezone(new \DateTimeZone(date_default_timezone_get()))
The other way would be to create date manually as below.
//2017-02-03T13:37:07.000+00:00
$currentDateTime = date('Y-m-d', time()).'T'.date('H:i:s', time()).'.000+00:00';
$mongoDate = new \MongoDate(strtotime($currentDateTime));
Upvotes: 0
Reputation: 241798
8Z
is not a valid way to express the time zone offset in ISO8601 format. The correct way would be:
2013-07-03T22:56:12-08:00
Except - for the date you provided, US Pacific Time is in Daylight Saving Time, and so -8
is not the correct offset. It should be -7
.
2013-07-03T22:56:12-07:00
You should understand that many time zones have more than one offset throughout the year. See "Time Zone != Offset" in the timezone tag wiki.
That said, I'm uncertain as to whether or not MongoDB supports time zone offsets, or if you are required to use UTC. Perhaps someone else can comment or answer on that aspect.
Upvotes: 3
Reputation: 9142
Your database dates should be in UTC; PHP should then adjust accordingly - usually with date_default_timezone_set
. Afterwards, you can take the date from the database and plug it into gmdate("y-m-d", strtotime($date))
for example.
Upvotes: 3