ユーザーのタイムゾーンを自動的に検出する

男が座って、ラジオを聞いています。

-モスクワの真夜中、午前6時のブラゴベシチェンスク、ウラジオストク、ハバロフスク、ユジノサハリンスク7、マガダン8、ペトロパブロフスク-カムチャツキー9時間。

男が座って、座ってから立ち上がって、後悔して言った:

-ああ、まあ、私たちの国の混乱!



テキストは、マヤックコールサインの音声記録から転載されます。

参考:ペトロパブロフスク-カムチャツキーでは、現在UTC + 11(夏のUTC + 12)であるため、モスクワ時間の深夜9時ではなく8時間になります。



サイトの多くの場所では、時間が表示されます。 多くの場合、GMT時間ではなく、サーバー時間ではなく、ユーザーのタイムゾーンの時間を表示するのが最適です。



多くの場合、可能なオプションの膨大なリストからタイムゾーンを選択することをお勧めします。 もちろん、この機会は楽しいものですが、サイトがユーザーのタイムゾーン自体を判断できる方が便利です。 ご想像のとおり、これを実行するのは非常に簡単です。JavaScriptを使用してUTCから現地時間を取得し、インデントし、XMLHttpRequestを使用してこのインデントをサーバーに渡すだけです。





さあ、試してください





新しいDjangoプロジェクトを作成します。 それをtepと呼びましょう-タイムゾーン実験プロジェクト。



django-admin startproject tep



新しいアプリケーションを追加します。



cd tep /

python manage.py startapp whattimeisit



次にsettings.pyを開き、最初に追加します。

輸入OS

SITE_ROOT = os.path.dirname(os.path.realpath(__ file__))



次に、テンプレートディレクトリへのパスを指定します。

TEMPLATE_DIRS =(

os.path.join(SITE_ROOT、「テンプレート」)、





そして、インストール済みのリストにアプリケーションを追加します。

INSTALLED_APPS =(

「django.contrib.auth」、

「django.contrib.contenttypes」、

「django.contrib.sessions」、

「django.contrib.sites」、

「django.contrib.messages」、

#次の行のコメントを解除して、管理者を有効にします。

# 'django.contrib.admin'、

「whattimeisit」、





また、データベースを示します。

データベース= {

'デフォルト':{

「ENGINE」:「django.db.backends.sqlite3」、#「postgresql_psycopg2」、「postgresql」、「mysql」、「sqlite3」または「oracle」を追加します。

'NAME': 'database'、#またはsqlite3を使用している場合はデータベースファイルへのパス。

}

}



そして、もちろん、settings.pyで指定したテンプレートディレクトリを作成します。



mkdirテンプレート/



そして、syncdbを実行します。



python manage.py syncdb



テンプレートディレクトリで、index.htmlテンプレートを作成します。



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title></title>

<script type="text/javascript" src="/static/jquery-1.4.2.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

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);

$(this).text(date.toLocaleString());

});

$.post('/please_set_timezone', { 'offset': time_zone });

});

</script>

</head>

<body>

<p>

{% if local_time %}

<b>{{ local_time }}</b>.

{% else %}

<b><span class="please_parse">{{ time }}</span></b>.

{% endif %}

</p>

</body>

</html>









次に、静的ファイル用のディレクトリを作成します。



mkdirメディア/



最終的にurls.pyは次のようになります。



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'),

)









jQueryをメディア/ディレクトリにロードする必要があります。 このディレクトリにjquery-1.4.2.min.jsを保存しました。



また、views.pyは次のようになりました。



# 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")

else:

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,})









実際、それは準備ができています。 これで、サーバーを起動して結果を確認できます。



python manage.py runserver



しかし、すぐに別のアイデア。 自動的に決定されたタイムゾーンに基づいて、選択する国と都市のリストを短くします。 もちろん、完全なリストを表示する機能があります-第一に、自動化が間違っている可能性があるため(たとえば、ユーザーのコンピューターの時刻が正しく設定されていない場合)、第二に、ユーザーは何らかの理由で一時的に別の国または別の国にいる可能性があるため街。



ユーザーがCookieを受け入れなくても、JavaScriptを使用してタイムゾーンの時刻が表示されるため、この方法は優れています。 Cookieを有効にしている場合、2番目のページからサーバー自体がローカル日付を提供します。




All Articles