Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automatically get the user's timezone from their browser time (for Django but works elsewhere).
{% load tz %}
<html>
<head>
<script>
{% get_current_timezone as TIME_ZONE %}
window.TIME_ZONE = '{{TIME_ZONE}}' // timezone server thinks we're in
function setCookie(name, value, days) {
let expires = ""
if (days) {
const expiry_date = (new Date()).setTime(date.getTime() + (days*24*60*60*1000))
expires = "; expires=" + expiry_date.toUTCString()
}
document.cookie = name + "=" + (value || "") + expires + "; path=/"
}
function setTimezoneCookie() {
if (window.gmt_offset) return
window.GMT_OFFSET = -(new Date).getTimezoneOffset()
window.setCookie('GMT_OFFSET', window.GMT_OFFSET, 365)
}
setTimezoneCookie()
</script>
</head>
<body>
Current timezone: {{TIME_ZONE}}
</body>
</html>
# settings.py:
MIDDLEWARE = [
'yourapp.middleware.AutoBrowserTimezoneMiddleware',
...
]
# yourapp/middleware.py:
from django.utils import timezone
def readTimezoneCookie(request, activate: bool=True):
gmt_offset = (self.request.COOKIES.get("GMT_OFFSET") or '').strip()
if gmt_offset.replace('-', '').isdigit():
tz = timezone.get_fixed_timezone(int(gmt_offset))
if activate:
timezone.activate(tz)
return tz
return None
def AutoBrowserTimezoneMiddleware(get_response):
def middleware(request):
readTimezoneCookie(request, activate=True)
return get_response(request)
return middleware
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment