4

What is the best way to display time according to the user's time zone?

I have a Post object:

class Post(models.Model):
   submit_date = models.DateTimeField(auto_now_add=True)
   ...

In the template I have something like this:

{% load tz %}
<p> TIME: {{ post_object.submit_date|localtime }} </p>

In settings.py:

USE_TZ = True
USE_L10N = True
TIME_ZONE = 'UTC'

Probably I'm missing something obvious, all I want is the template to display the user's time depending on its timezone. Should I do some logic on the views.py file?

Alejandro Veintimilla
  • 10,743
  • 23
  • 91
  • 180

1 Answers1

2

It depends on django version and on user time zone. If you have user time zone stored in user's profile or somewhere else you can use timezone template tag:

{% timezone "Europe/Paris" %}
    Paris time: {{ value }}
{% endtimezone %}

Or you can use timezone filter:

{{ value|timezone:"Europe/Paris" }}

Otherwise you'll have to find out what's user's timezone is (by her ip I think). So you can use solution provided by fasouto here (but it's not reliable for it returns first timezone for the country, and there are countries with several time zones).

PS: I think that best bet is to ask user for her time zone and store it for it's sure way to provide proper date/time display for her.

Community
  • 1
  • 1
sepulchered
  • 814
  • 7
  • 18