I am building an application in Django which allows the end-user to retrieve information which is sensitive to the time of day (12 am to 12 am) on a given day. I store this
Django doesn't detect end user's timezone. But what it does is pretty clever.
Consider this:
Client | Server | UTC
time 9:00 am | time 12:00 pm | time 7:00 am
timezone UTC+2:00 | timezone UTC+5:00 |
As you can see, the server and client are in different timezones and therefore have different local time.
Now, let's say the client makes a request to create a new object in your database. This object has a date field. So what Django does is, it saves the object's date under UTC.
How does that work?
Django will first take the server's local time, that is 12:00 am. Then it will convert it to UTC time by subtracting 5 hours which becomes 7:00 am. And this is the time that Django will use to save the object.
Now, let's say later, the client wants to see at what time did he create that object.
The object's creation time is 7:00 am UTC
. To display the object's creation time to your client, you can either use the app linked by Jason in another answer. But I don't find timezone lookup using IP very reliable as the user could be using a proxy.
OR, you can render the time in UTC and use some JavaScript to convert it to Client's local time. Since, JS runs on browser, it will accurately pick client's timezone from their computer.
Finally, when you convert 7:00 am UTC
to the client's timezone, by adding 2 hours (as it is 2 hours ahead of UTC), the client will see the object's creation time as 9:00 am
which is what they expected.
Not only, that, if there's another client on the other side of the Earth in UTC-5:00
timezone, you can display the object's time to them by subtracting 5 hours which would give 2:00 am
. So, according to that user, it was added at 2:00 am.
No. There are some packages where you can detect timezone based on IP address. You can look at https://github.com/adamcharnock/django-tz-detect