Does Django automatically detect the end user's timezone?

南笙酒味 提交于 2019-11-29 14:29:41

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!