Reputation: 5263
I just migrated a Symfony2.4 project to Symfony3.0 and I am facing a wierd situation.
The project's default timezone is UTC, everything is stored as UTC timestamps in the MYSQL database.
I retrieve an entry with a datetime field named 'checkOut', pass it to the twig template:
<p>{{ dump(entity.checkOut) }}</p>
<p>{{ dump(entity.checkOut.getTimestamp()) }}</p>
And I get:
DateTime {#585 ▼
+"date": "2016-09-17 10:46:00.000000"
+"timezone_type": 3
+"timezone": "UTC"
}
1474109160
which is correct.
But my app should support users from different timezones. So I store a users preferred timezone and use an event listener to set it
date_default_timezone_set($this->token_storage->getToken()->getUser()->getTimezone());
After that the same entry displays:
DateTime {#585 ▼
+"date": "2016-09-17 10:46:00.000000"
+"timezone_type": 3
+"timezone": "Asia/Jakarta"
}
1474083960
This is clearly wrong as the timestamp is now different. I would expect this:
DateTime {#585 ▼
+"date": "2016-09-17 17:46:00.000000"
+"timezone_type": 3
+"timezone": "Asia/Jakarta"
}
1474109160
This used to work fine in sf2.4. Can Anyone explain what the problem is and how can I work around it?
Upvotes: 1
Views: 1223
Reputation: 18440
That's because you are changing the default timezone of your server rather than changing the timezone of the DateTime instance in question. One of my pet hates!
I am not familiar with twig, but doing something like this would give you the expected result:-
<p>{{ dump(entity.checkOut) }}</p>
<p>{{ dump(entity.checkOut.setTimeZone(new \DateTimeZone("Asia/Jakarta"))) }}</p>
<p>{{ dump(entity.checkOut.getTimestamp()) }}</p>
Upvotes: 4