1

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?

0

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. This is indeed a solution but would require me to update every template on the website. Also there are cases where for example I have to get all records of a specific month and in those cases I should also take into account the user's timezone. Changing the default timezone is very convenient because everything is calculated with the user's timezone.
Convenient yes, but still wrong as you are experiencing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.