I'm using Nette with Kdyby/Doctrine. I need to store datetimes and to show them to the users in their timezone. What is the best way, how to do that? I mean, is there an easy way how to convince doctrine to convert datetime into UTC before writing it into database and how to easily obtain user timezone to render the datetime (using latte).
- Member | 555
Hi, you must do couple of things to correctly display time in your app:
1. setup timezone of the server/application
Set this line to correct value by the geolocation of the server. If your server is in Frankfurt for example, set it to
Europe/Berlin. If you are the administrator of
the server, install/setup NTP daemon too, so the server clocks are always at
2. allow user to set their timezone
you must provide user with some sort of timezone setup. Screen like this:
You must create this list of all possible timezones (use that wiki page link above).
3. store all date-time events/data as timestamp
Timestamp is best when dealing with timezones, because timestamp is timezone independent. You can convert timestamp into timezone time with code below.
4. display date-time event/date in users' timezone
$userTimezone = 'Asia/Ashgabat'; // get this from DB, step 2 $postCreatedAt = 1495971234; // timestamp of date-time event you want to display, step 3 $datetimeObj = new Nette\Utils\DateTime(); $datetimeObj->setTimestamp($postCreatedAt); $datetimeObj->setTimezone(new DateTimeZone($userTimezone)); echo $datetimeObj->format('Y-m-d H:i:sP') . "\n"; // 2017-05-28 16:33:54+05:00
Last edited by srigi (2017-05-28 13:47)
- ok, done already
- Do I have to allow the user to edit the timezone? I would prefer to obtain it auto-magicaly from the user request.
- ok, I am planning to use UTC DateTime, but it should be the same
- ok, so I have to edit all latte templates and server site work with date
I did a little hack.
- I set up the server timezone to UTC – now all datetimes stored in database as well as all datetimes created via new \DateTime are concidered as UTC
- I've used https://bitbucket.org/…mezonedetect which will determine the timezone on the client side and sends it to me on server (first time only for the current session)
- I only have to update all usage to set the obtained timezone
If this won't be enough for client, we'll add the timezone settings to the registration form (but even then, we have to decide the timezone for non registered users)…