HTML/JS template filter to show localized dates/times

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# ./utils/localdatetimefilters.py
from time import mktime
from google.appengine.ext import webapp

def localdate(value, arg=None):
    from django.conf import settings
    from django.template import defaultfilters
    if not value:
        return ''
    if arg is None:
        arg = settings.DATE_FORMAT
    content = '''<script type="text/javascript">document.write(new Date(%d).toLocaleDateString().replace(/\s[A-Z]{3}\+[0-9]{4}/, '').replace(/\s\([\s\w]+\)/, ''));</script><noscript>%s</noscript>''' % (
        mktime(value.utctimetuple())*1000,
        defaultfilters.date(value, arg)
    )
    return content

def localtime(value, arg=None):
    from django.conf import settings
    from django.template import defaultfilters
    if not value:
        return ''
    if arg is None:
        arg = settings.TIME_FORMAT
    content = '''<script type="text/javascript">document.write(new Date(%d).toLocaleTimeString().replace(/\s[A-Z]{3}\+[0-9]{4}/, '').replace(/\s\([\s\w]+\)/, ''));</script><noscript>%s</noscript>''' % (
        mktime(value.utctimetuple())*1000,
        defaultfilters.time(value, arg)
    )
    return content

def localdatetime(value, arg1=None, arg2=None):
    from django.conf import settings
    from django.template import defaultfilters
    if not value:
        return ''
    if arg1 is None:
        arg1 = settings.DATE_FORMAT
    if arg2 is None:
        arg2 = settings.TIME_FORMAT
    content = '''<script type="text/javascript">document.write(new Date(%d).toLocaleString().replace(/\s[A-Z]{3}\+[0-9]{4}/, '').replace(/\s\([\s\w]+\)/, ''));</script><noscript>%s %s</noscript>''' % (
        mktime(value.utctimetuple())*1000,
        defaultfilters.date(value, arg1),
        defaultfilters.time(value, arg2)
    )
    return content

register = webapp.template.create_template_register()
register.filter(localdate)
register.filter(localtime)
register.filter(localdatetime)

# ./main.py (Request handler)
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

def main():
    webapp.template.register_template_library('utils.localdatetimefilters')

More like this

  1. Querying datetime aware objects in your local timezone by jayliew 1 year, 10 months ago
  2. UTC-based astimezone filter by miracle2k 2 years, 5 months ago
  3. astimezone template tag by whardier 3 years, 1 month ago
  4. Client-side Django-style date & time string formatting by robbie 7 years, 1 month ago
  5. Converting datetime to Javascript milliseconds in epoch by guychi 6 years, 7 months ago

Comments

ramusus (on April 16, 2009):

So many equal rows in code! What about DRY principle?

#

(Forgotten your password?)