📜 ⬆️ ⬇️

Automatic detection of user's time zone

A man sits listening to the radio.
- It is midnight in Moscow, 6 am in Blagoveshchensk, 7 in Vladivostok, Khabarovsk, Yuzhno-Sakhalinsk, 8 in Magadan, 9 hours in Petropavlovsk-Kamchatsky.
A man sits, sits, then rises, and says with some regret:
- Oh, well, a mess in our country!

The text is reprinted from the audio recording of the beacon "Mayak".
For reference: now in Petropavlovsk-Kamchatsky is now UTC + 11 (in summer UTC + 12), so now at midnight Moscow time there would be 8 hours, not 9.

In many places on the site displays time. And in many cases it is best to display not GMT time, not server time, but time in the user's time zone.
Often it is proposed to choose your time zone from a huge list of possible options. Of course, the opportunity is pleasant, but it is more convenient if the site can determine the user's time zone by itself. And, as you can guess, it is not difficult to do this - it is enough to get local time and indent from UTC using JavaScript and transfer this indent to the server using XMLHttpRequest.

Next, try

Create a new Django project. Let's call it tep - timezone experiment project.

django-admin startproject tep

Add a new application.

cd tep /
python manage.py startapp whattimeisit

Now open settings.py and add at the beginning:
import os
SITE_ROOT = os.path.dirname (os.path.realpath (__ file__))

Now specify the path to the template directory:
os.path.join (SITE_ROOT, 'templates'),

And add our application to the list of installed:
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',

And also indicate the database:
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'database', # Or path to database file if using sqlite3.

And, of course, create a template directory, which we specified in settings.py.

mkdir templates /

And run syncdb.

python manage.py syncdb

In the template directory, create a template index.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="/static/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var time_zone = (new Date().getTimezoneOffset()/60)*(-1);
var dateoffset = time_zone*60*60*1000;
$('span.please_parse').each(function() {
var date = new Date($(this).text());
date.setTime(date.getTime() + dateoffset);
$.post('/please_set_timezone', { 'offset': time_zone });
{% if local_time %}
<b>{{ local_time }}</b>.
{% else %}
<b><span class="please_parse">{{ time }}</span></b>.
{% endif %}

Now create a directory for static files.

mkdir media /

urls.py as a result of this:

from django.conf.urls.defaults import *
import os
from settings import SITE_ROOT

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
# Example:
# (r'^tep/', include('tep.foo.urls')),

# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),

(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(SITE_ROOT, 'media')}),

(r'^$', 'whattimeisit.views.index'),
(r'^please_set_timezone$', 'whattimeisit.views.please_set_timezone'),

In the media / directory you need to load jQuery. I saved to this directory jquery-1.4.2.min.js.

And views.py turned out like this:

# Create your views here.

from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from datetime import datetime
from datetime import timedelta

def please_set_timezone(request):
if request.is_ajax():
timezone_offset = request.POST.get('offset', False)
if timezone_offset:
request.session['timezone_offset'] = timezone_offset
message = "OK"
return HttpResponse(message)
return HttpResponseRedirect(reverse('whattimeisit.views.index'))

def index(request):
time = datetime.utcnow()
timezone_offset = request.session.get('timezone_offset', False)
if timezone_offset:
offset = timedelta(hours=int(timezone_offset))
local_time = time+offset
local_time_string = local_time.strftime("%d.%m.%Y %H:%M:%S")
local_time_string = False
time_string = time.strftime("%m/%d/%Y %H:%M:%S")
return render_to_response("index.html", {'time': time_string, 'local_time': local_time_string,})

That, in fact, is ready. Now you can start the server and see the result.

python manage.py runserver

But immediately another idea. Based on an automatically defined time zone, shorten the list of countries and cities to choose from. Of course, with the ability to display the full list - because, firstly, the automation may be wrong (if, for example, the time on the user's computer is set incorrectly), secondly, the user may simply for some reason be temporarily in another country or in another the city.

This method is good because even if a user does not accept cookies, it will still show the time in his time zone using JavaScript. If his cookies are enabled, then from the second page the server itself will give it its local date.

Source: https://habr.com/ru/post/102506/

All Articles