I would like to know if there is a way to automatically retrieve user's timezone from client. Especially during login.
I tried to add this in the login page (using auth.login
):
{% get_current_timezone as TIME_ZONE %}
and then add this in the login form
<input type="hidden" name="next" value="/redirect/?tz={{ TIME_ZONE }}">
but tz
is always the timezone of the server.
The solution to this problem is to use UTC in the code and use local time only when interacting with end users. Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. In Django 5.0, time zone support will be enabled by default.
You can set any specific time zone using the PHP function date_default_timezone_set . This sets the specified time zone for users. Basically the users' time zone is goes to the client side, so we must use JavaScript for this.
timezone. now() useful. This function returns the current date and time as a naive datetime when USE_TZ = False and as an aware datetime when USE_TZ = True .
Django stores datetime information in UTC in the database, uses timezone-aware datetime objects internally, and translates them to the end user's time zone in templates and forms.
I've simplified it even further, and you can plug in in here: https://github.com/Miserlou/django-easy-timezones or http://gun.io/blog/django-easy-timezones/
From the documentation:
Selecting the current time zone
The current time zone is the equivalent of the current locale for translations. However, there's no equivalent of the Accept-Language HTTP header that Django could use to determine the user's time zone automatically. Instead, Django provides time zone selection functions. Use them to build the time zone selection logic that makes sense for you.
You can try setting timezone cookie via javascript by utilizing getTimezoneOffset function or try to do some geoip magic and figure timezone by location. Probably the most reliable way would be to ask the user directly and save this information in user profile/session.
I was hunting around for the sam thing yesterday. In the end I ended up putting together a Django app to what BluesRockAddict suggests above (i.e. use getTimezoneOffset):
https://github.com/adamcharnock/django-tz-detect
I hope someone finds that useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With